ThreadPoolExecutor + Runnable
来源:互联网 发布:java list 拼接字符串 编辑:程序博客网 时间:2024/06/07 22:43
概述
在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。
阅读全文
0 0
- ThreadPoolExecutor + Runnable
- java多线程1(Thread,Runnable,ThreadPoolExecutor)
- Java中的命令模式——Thread,ThreadPoolExecutor和Runnable
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- ThreadPoolExecutor
- Leetcode:Insert Delete GetRandom O(1)
- 大数据学习记录(day6)-图说Mapreduce工作机制
- 【模板】树的直径 DP (模板题:XJOI数字转换)
- JVM学习06:运行时数据区域-运行时常量池
- 561. Array Partition I
- ThreadPoolExecutor + Runnable
- 混淆矩阵,机器学习评价准则,ROC曲线-阈值评价标准
- SDUT 1007--> Financial Management
- 学习笔记
- Android开机Activity的渐变效果
- svdRec 源码
- JAVA高级工程师课程笔记整理——(十二)jquery和ajax
- 修改hosts文件
- CC1101