newCachedThreadPool线程池的使用

newCachedThreadPool是ThreadPoolExecutor的一种实现。如代码:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

模拟上厕所: // 线程同时执行,不等待

@Slf4j
public class WashRoom implements Runnable {
    private int n; // 用来记录第几个人
    @Override
    public void run() {
        try {
            log.info(n+" 开始");
            int milliSecond = RandomUtils.createMilliSecond(1, 4); // 这里只要是随机秒数就行
            Thread.sleep(milliSecond);
            log.info(n +"结束,用时: "+milliSecond);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public WashRoom(int n){
        this.n=n;
    }

    public static void main(String[] args) {
//        ExecutorService executorService = Executors.newCachedThreadPool(); // 这行 和下面代码  作用一样
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                0,      //  核心线程池数量
                Integer.MAX_VALUE,    //  线程池最大数量
                60L,    // 当线程池数量大于core时,1分钟内,如果没有其他线程来使用多余的线程,就会释放,可以理解为是为了避免频繁的启动和停止线程
                TimeUnit.SECONDS,   // 单位
                new SynchronousQueue<Runnable>()    //   阻塞队列的具体实现
        );
        for (int i = 0; i < 5; i++) {  // 5个人上厕所
            executorService.execute(new WashRoom(i));
        }
        executorService.shutdown(); // 别忘了关闭

    }
}
发布了422 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/enthan809882/article/details/104037101