//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
そこでしばらく待ってから先に進みます。なんで?そこでは何が起こりますか?それは必要ですか?