关闭线程池

关闭线程池
代码如下:

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)

猜你喜欢

转载自blog.csdn.net/weixin_42335535/article/details/85988205