终止期间线程延迟

时间:2013-05-09 18:04:41

标签: java multithreading

//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

等待一段时间,然后继续前进。为什么?那里发生了什么?这有必要吗?

1 个答案:

答案 0 :(得分:2)

如果execProductNumberExecutorService,那么您需要在最后一个作业提交到服务后立即致电shutdown()。此允许任何已提交的作业完成。

  

并且程序不会立即终止

右。它已到达main()的末尾,但与ExecutorService关联的线程是非守护进程,并且它仍在运行。通过调用execProductNumber.shutdown();,您的应用程序将在ProductNumber任务完成后立即完成。

  

在尝试调试时,我发现它延迟了(ThreadPoolExecutor.java):

是的,工作线程正在耐心地等待另一个任务提交给线程池。

相关问题