1. 程式人生 > >關閉執行緒池

關閉執行緒池

關閉執行緒池
程式碼如下:

public class ClosePoolTest {
    public static final Logger LOG = LoggerFactory.getLogger(ClosePoolTest.class);

    public static void main(String[] args) {

        ExecutorService pool = Executors.newFixedThreadPool(10);
        final long waitTime = 5 * 1000;
        final long awaitTime =
5 * 1000; Runnable task1 = new Runnable() { public void run() { try { LOG.info("task1 start"); Thread.sleep(waitTime); LOG.info("task1 end"); } catch (InterruptedException e) { LOG
.error("task1 interrupted: [{}]", e.getMessage()); } } }; Runnable task2 = new Runnable() { public void run() { try { LOG.info(" task2 start"); Thread.sleep(1000); LOG.info
(" task2 end"); } catch (InterruptedException e) { LOG.error("task2 interrupted: [{}]", e.getMessage()); } } }; long start = System.nanoTime(); // 讓學生解答某個很難的問題 pool.execute(task1); // 生學生解答很多問題 for (int i = 0; i < 50; ++i) { pool.execute(task2); } // pool.shutdown(); try { // 向學生傳達“問題解答完畢後請舉手示意!” pool.shutdown(); // 向學生傳達“XX分之內解答不完的問題全部帶回去作為課後作業!”後老師等待學生答題 // (所有的任務都結束的時候,返回TRUE) if (!pool.awaitTermination(awaitTime, TimeUnit.MILLISECONDS)) { // 超時的時候向執行緒池中所有的執行緒發出中斷(interrupted)。 pool.shutdownNow(); } } catch (InterruptedException e) { //InterruptedException // awaitTermination方法被中斷的時候也中止執行緒池中全部的執行緒的執行。 System.out.println("awaitTermination interrupted: " + e); pool.shutdownNow(); } System.out.println("end"); // 執行時間 System.out.println((System.nanoTime() - start) / 1000000 + "msces"); } }

原文請檢視:
(https://blog.csdn.net/alinshen/article/details/78090043)