awaitTermination()使程序睡眠

时间:2014-02-04 10:48:35

标签: java multithreading threadpool executorservice executor

class SomeClass {

 void go() {

 //do stuff
shutdownAndAwaitTermination(pool);

System.exit(0);

    }    

public void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); 
        try {
            logger.log(Level.INFO, "Waiting for existing tasks to terminate");
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow();

                if(!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                    logger.log(Level.SEVERE, "  ERROR: pool did not terminate");
                }
            }   
        } catch (InterruptedException ie) {
             // (Re-)Cancel if current thread also interrupted
             pool.shutdownNow();
             // Preserve interrupt status
             Thread.currentThread().interrupt(); 
           }
       }

  }//end class

我试图安全优雅地关闭我的游泳池,而不会冒着不能终止的风险。我需要了解你的专家8-)。当我致电shutdownAndAwaitTermination()时,我对if (!pool.awaitTermination(60, TimeUnit.SECONDS))阻止感到困惑。当该行在方法go()中出现时,应用程序是否在系统存在之前等待60秒(等待终止)?

2)你能解释一下catch块中会发生什么吗?

1 个答案:

答案 0 :(得分:1)

1)不会等待最多60秒,但如果所有任务都完成,也可以在30秒后返回。

2)如果当前线程被中断,则告诉thred池现在关闭,让执行的任务继续执行。比你再次打断以保留线程属性