//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
在那里等了一段时间,然后继续前进。为什么?那里会发生什么?那有必要吗?