资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

如何正确的使用ThreadPoolExecutor线程池

如何正确的使用ThreadPoolExecutor线程池,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联-专业网站定制、快速模板网站建设、高性价比秦皇岛网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式秦皇岛网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖秦皇岛地区。费用合理售后完善,十余年实体公司更值得信赖。


import java.util.Random;
import java.util.concurrent.*;

public class PoolTest {

    private BlockingQueue workingQueue = new ArrayBlockingQueue(10);
    private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    private  ExecutorService threadPool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, workingQueue, rejectedExecutionHandler);
    private Random random = new Random();

    public void test() {
        int size = 10;
        final CountDownLatch latch = new CountDownLatch(size);
        for(int i = 0; i < size; i ++) {
            threadPool.execute(new Runnable() {
                int x = random.nextInt(10);
                @Override
                public void run() {
                    try {
                        plus(x,x);
                    } finally {
                        latch.countDown();
                    }

                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("线程全部执行完成");
        }

        threadPool.shutdown();
    }


    public void plus(int x, int y) {
        System.out.println("sum = " + (x + y));
    }


    public static void main(String[] args) {
        PoolTest poolTest = new PoolTest();
        poolTest.test();
    }
}

看完上述内容,你们掌握如何正确的使用ThreadPoolExecutor线程池的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


新闻标题:如何正确的使用ThreadPoolExecutor线程池
新闻来源:http://cdkjz.cn/article/gosojh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220