java-线程池-工具类
来源:互联网 发布:鼎力测试软件 编辑:程序博客网 时间:2024/06/03 23:48
汇总JDK自带的四个常用线程池的用法
package thread.pool;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ThreadPoolUtil { static ExecutorService cachedThreadPool; static ExecutorService fixedThreadPool; static ScheduledExecutorService scheduledThreadPool; static ExecutorService singleThreadPool; static ExecutorService cachedThreadPoolRun(Runnable runnable) { if (cachedThreadPool == null) cachedThreadPool = Executors.newCachedThreadPool(); cachedThreadPool.submit(runnable); return cachedThreadPool; } public static ExecutorService fixedThreadPoolRun(Runnable runnable) { if (fixedThreadPool == null) fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime() .availableProcessors()); fixedThreadPool.submit(runnable); return fixedThreadPool; } public static ExecutorService scheduledThreadPoolRun(Runnable runnable, long delay, TimeUnit unit) { if (scheduledThreadPool == null) scheduledThreadPool = Executors.newScheduledThreadPool(Runtime.getRuntime() .availableProcessors()); scheduledThreadPool.schedule(runnable, delay, unit); return scheduledThreadPool; } public static ExecutorService singleThreadPoolRun(Runnable runnable) { if (singleThreadPool == null) singleThreadPool = Executors.newSingleThreadExecutor(); singleThreadPool.submit(runnable); return singleThreadPool; } public static void main(String[] args) { final Long startTime = System.currentTimeMillis(); ExecutorService executorService = null; for (int i = 0; i < 1000000; i++) {// System.out.println(finalI); final int finalI = i; Runnable task = () -> System.out.println(finalI); executorService = ThreadPoolUtil.fixedThreadPoolRun(task); } if (executorService != null) { executorService.shutdown(); } while (true) { if (executorService.isTerminated()) { System.out.println("所有的子线程都结束了!"); break; } } final Long stopTime = System.currentTimeMillis(); System.out.println("---------------------------"); System.out.println(stopTime - startTime); }}
0 0
- java-线程池-工具类
- Java:线程并发工具类
- java-线程-定时器-工具类
- Java:线程并发工具类
- 线程池工具类
- 工具类-线程池
- java线程池工具类代码(利用java官方线程池类ExecutorService实现)
- Java Executors工具线程池的使用
- java HashMap 线程安全 工具类
- java线程同步工具类总结
- java线程:几个实用的线程工具类
- 线程池相关工具类
- 线程池命名工具类
- Java线程CPU亲和性工具
- Java线程Dump分析工具
- Java线程同步工具-ArrayBlockingQueue
- Java线程同步工具-CountDownLatch
- Java线程同步工具-CyclicBarrier
- DOS中的echo命令使用详情
- jQuery对select的基本操作
- 笔记——android实现VR视频显示和优化
- Unity面试题(含答案)
- mysql FIND_IN_SET查询 字段,拼接数据是否存在某个值 in查询字段存在某个数组中
- java-线程池-工具类
- 在VS2013中配置OpenCV
- RxSwift (2) Subject
- 二叉搜索树转排序双向链表
- PHP分页机制
- Java for Web学习笔记(四一):Filter(3)用于Log
- UML-类图
- 分布式消息队列
- AndroidStudio出现tools:replace="android:theme"问题