WorkStealingPool的使用简析

WorkStealingPool的作用

这是Java8新增的创建线程池的方法,如果不主动设置它的并发数,那么这个方法就会以当前机器的CPU处理器个数为线程个数,这个线程池会并行处理任务,不能够保证任务执行的顺序。

示例代码

public class TestMain {
    //格式化
    static SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //AtomicInteger用来计数
    static AtomicInteger number = new AtomicInteger();

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newWorkStealingPool();
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("第" + number.incrementAndGet() + "周期线程运行当前时间【" + sim.format(new Date()) + "】");
                }
            });
        }
        System.out.println("主线程运行当前时间【" + sim.format(new Date()) + "】");
    }
}

运行结果:

在这里插入图片描述

可以看到是几个任务是并行执行且无序的。

如果传入并发数为2,看看结果:

ExecutorService executorService = Executors.newWorkStealingPool(2);

运行结果:

在这里插入图片描述

可以看到第三个周期任务根本就不会被执行了。

总结

可以看出WorkStealingPool这个方法会以当前机器的CPU处理器个数为线程个数,这个线程池会并行处理任务,且不保证顺序,同时并发数能作为参数设置,而任务如果想要都执行就要设置和任务数量对应的并发数。

发布了208 篇原创文章 · 获赞 204 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/104494564