//Main.java
public static boolean isEnd() {
return end;
}
public static void main(String[] args) {
execProductNumber.execute(new ProductNumber(allBuffer));
end = true;
System.out.println("Leaving main");
//execProductNumber.shutdown();
}
//ProductNumber.java
public void run() {
while(!Main.isEnd()) {
//something
}
System.out.println("Leaving thread");
}
我正在开始我的程序,得到输出:
Leaving main
Leaving thread
并且程序不会立即终止(我需要等待大约1.5分钟才能成功结束程序)。当我试图通过shutdown()(注释)停止线程时,它立即停止。在尝试调试时,我发现它延迟了(ThreadPoolExecutor.java):
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) { //here
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
等待一段时间,然后继续前进。为什么?那里发生了什么?这有必要吗?
答案 0 :(得分:2)
如果execProductNumber
是ExecutorService
,那么您需要在最后一个作业提交到服务后立即致电shutdown()
。此将允许任何已提交的作业完成。
并且程序不会立即终止
右。它已到达main()
的末尾,但与ExecutorService
关联的线程是非守护进程,并且它仍在运行。通过调用execProductNumber.shutdown();
,您的应用程序将在ProductNumber
任务完成后立即完成。
在尝试调试时,我发现它延迟了(ThreadPoolExecutor.java):
是的,工作线程正在耐心地等待另一个任务提交给线程池。