JAVA创建线程池

文章通过两个示例展示了如何使用ThreadPoolExecutor的execute()和submit()方法来执行任务,并结合CountDownLatch进行同步控制,确保所有任务执行完毕后再继续后续操作。这两种方法都是线程池处理任务的方式,但submit()会返回Future对象,可用于获取任务执行结果。
摘要由CSDN通过智能技术生成

方法一: threadPool.execute()

    public static void main(String[] args) throws Exception {
        // 初始化线程池, 参数一定要一定要一定要调好!!!!
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 50,
                4, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());

        // 记录单个任务的执行次数
        int number = 10;
        CountDownLatch countDownLatch = new CountDownLatch(number);
        for (int i = 0; i < number; i++) {
            int finalI = i;
            threadPool.execute(new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程"+ finalI +"执行任务...");
                    // 任务个数 - 1, 直至为0时唤醒await()
                    countDownLatch.countDown();
                }
            }));
        }
        // 让当前线程处于阻塞状态,直到锁存器计数为零
        countDownLatch.await();
        // 关闭线程池
        threadPool.shutdown();
        System.out.println("线程全部执行完成");
    }

方法二:threadPool.submit();

    public static void main(String[] args) throws Exception {
        // 创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20,
                0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1024));
        // 记录单个任务的执行次数
        final int number = 10;
        CountDownLatch countDownLatch = new CountDownLatch(number);
        for (int i = 0; i < number; i++) {
            int finalI = i;
            threadPool.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("线程"+ finalI +"执行任务...");
                    // 任务个数 - 1, 直至为0时唤醒await()
                    countDownLatch.countDown();
                }
            }));
        }
        // 让当前线程处于阻塞状态,直到锁存器计数为零
        countDownLatch.await();
        // 关闭线程池
        threadPool.shutdown();
        // 打印结果
        System.out.println("线程池任务执行完成!");
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值