我对Java /线程不熟悉,并继承了以下代码。这是一个命令行程序,main()仅启动5-6种不同类型的线程,并使用^C退出。我想添加一个关闭钩子来正确关闭所有线程,并将其修改为以下方式。
我在所有线程中都添加了Shutdown钩子和stopThread()方法(例如MyWorker类中的方法)
问题是当我按下^C时,我看不到线程run方法的结束消息。这是在后台完成还是我的方法有问题?此外,是否有更好的模式我应该遵循?
谢谢
public class Main {
public static MyWorker worker1 = new MyWorker();
// .. various other threads here
public static void startThreads() {
worker1.start();
// .. start other threads
}
public static void stopThreads() {
worker1.stopThread();
// .. stop other threads
}
public static void main(String[] args)
throws Exception {
startThreads();
// TODO this needs more work (later)
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
stopThreads();
} catch (Exception exp) {
}
}
});
} }
public class MyWorker extends Thread {
private volatile boolean stop = false;
public void stopThread() {
stop = true;
}
public void run() {
while (!stop) {
// Do stuff here
}
// Print exit message with logger
}
}
stop
声明为volatile
。 - Tudor