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秒,则线程应被杀死,程序应正确结束吗?

最佳答案

不。超时是您要等待的时间。当执行所有任务时,线程池将终止。

如果调用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;
    }
}

关于java - 线程池中的awaitTermination不会终止线程池,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18391874/

10-08 23:21