threadpool中的awaitTermination不会终止线程池

时间:2013-08-22 22:33:35

标签: java multithreading

 if (isDownloadLogRequired) {
        ExecutorService pool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        for (HostGenericServiceTicket hostGenericServiceTicket : hostGenericServiceTickets) {
            pool.submit(new DiagnosticLogDownloader(logNames, downloadTo, hostGenericServiceTicket));
        }
        pool.shutdown();
        try {
            pool.awaitTermination(downloadTimeout, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.err.println(MessageFormat.format("{0}: Reason: {1}", e.getClass()
                    .getSimpleName(), e.getMessage()));
        }
    }

如果downloadTimeout设置为180秒,线程应该被杀死,程序应该结束吗?

1 个答案:

答案 0 :(得分:4)

没有。超时是你想要等多少。线程池将在执行完所有任务后终止。

如果您调用shutdown(),则线程池不会将新作业排入队列(但它不会停止正在运行的作业,并且将运行已经入队的作业)。

如果您致电shutdownNow(),它将无法启动任何新作业,并会向工作线程发送中断。如果您的Runnable正确检查中断并自动终止,则池将快速停止。否则,它等同于shutdown()

在Java中,没有办法强制终止线程(Thread.stop()已被弃用,因为它的资源泄漏和容易出现死锁)。您只能要求线程终止(调用其interrupt()方法),但由您的代码定期检查Thread.interrupted()并正确使用InterruptedException s。

礼貌工作者的一个例子是:

public class PoliteWorker implements Runnable {
    private boolean successful = false;
    public void run() {
        while (...) {
            if (Thread.interrupted()) {
                myLogger.log(Level.INFO, "Thread was interrupted. Aborting...");
                return;
            }
            ...
            try {
                String line = myInput.readLine();
            } catch (InterruptedIOException ex) {
                //Must terminate
                myLogger.log(Level.INFO, "Thread was interrupted. Aborting...", ex);
                return;
            } catch (IOException ex) {
                //handle other exceptions
            }
        }
        successful = true;
    }
}
相关问题