ThreadPoolExecutor + Runnable

概述


ThreadPoolExecutor 并发调用 一文中介绍了ThreadPoolExecutor + Callable的方法并行执行task,其实ThreadPoolExecutor还有另一种用法,
ThreadPoolExecutor + Runnable。如果你不理会task执行的结果,可以使用这种方法。


代码


public class TestExecutorCountDown {

    public static void main(String[] args) throws InterruptedException {
        List<Long> list = Arrays.asList(1L,2L,3L);
        for (final Long ele : list) {
            Runnable task = new Runnable() {
                public void run() {
                    process(ele);
                }
            };
            ThreadPool.getThreadPool().execute(task);
        }
    }

    private static void process(Long ele) {
            System.out.println(ele);
    }
}


public class ThreadPool {
    private static final int CORE_SIZE = 8;

    private static final int MAX_SIZE = 12;

    private static final long KEEP_ALIVE_TIME = 30;

    private static final int QUEUE_SIZE = 50000;

    private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_SIZE,    MAX_SIZE, KEEP_ALIVE_TIME,TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy());

    public static ThreadPoolExecutor getThreadPool() {
        return threadPool;
    }
}

使用ThreadPoolExecutor + Runnable这种方式是没法获取到task中的返回值的。因为run方法是返回类型是void的。


利用CountDownLatch 阻塞主线程


ThreadPoolExecutor 并发调用 一文中,使用了ThreadPoolExecutor中的invokeAll方法,可以指定执行的任务的超时时间,但是该方法只接收Callable类型的task。Runnable类型的task无法传入。

如果使用ThreadPoolExecutor + Runnable的方法,想等待所有子线程都执行完后,再执行某些业务操作,可以使用CountDownLatch。

这里写图片描述

在每个task执行完后,在finally里面,将countDownLatch计数器减1,countDownLatchde await方法会一直阻塞,直到计数器的count变成0。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值