概述
在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。