线程池单例类
2016-06-13 20:00
190 查看
package com.study.googleplay.manager; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; import java.util.concurrent.TimeUnit; public class ThreadManager { /** * 线程池 * * @author TCL * @date 2016-6-13 */ private static ThreadPool threadPoolpool; public static ThreadPool getInstance() { if (threadPoolpool == null) { synchronized (ThreadManager.class) { if (threadPoolpool == null) { int threadCount = Runtime.getRuntime() .availableProcessors() * 2 + 1;// 线程个数 threadPoolpool = new ThreadPool(threadCount, threadCount, 1L); } } } return threadPoolpool; } public static class ThreadPool { private int corePoolSize;// 核心线程数 private int maximumPoolSize;// 最大线程数 private long keepAliveTime;// 休息时间 private ThreadPoolExecutor executor; private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) { this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = keepAliveTime; } public void execute(Runnable r) { // 参数1:核心线程数,参数2:最大线程数,参数3:休息时间,参数4:时间单位, // 参数5:线程队列参数6:生产线程的工厂,参数7:线程异常策略 if (executor == null) { executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), Executors.defaultThreadFactory(), new AbortPolicy()); } executor.execute(r);// 执行一个Runnable对象,具体执行时机由线程池说了算 } // 取消任务 public void cancel(Runnable r) { if (r != null) { // 如果任务还没开始,正在等待,可以通过 此方法移除, // 如果任务已经开始,需要在run方法中进行中断 executor.getQueue().remove(r);// 从线程池中移除对象 } } } }
相关文章推荐
- js操作数组方法大全
- 4——虚拟机体验之Xen篇——令人脑洞大开的奇异架构
- 侧边栏导航
- Bzoj3270:博物馆:概率与期望,高斯消元
- 基于IOS平台的游戏之打地鼠
- 迭代加深搜索 POJ 1129 Channel Allocation
- Spring MVC(Spring Boot框架)快速入门
- (转)SVN详解
- XTOJ1250Super Fast Fourier Transform
- 酒店管理系统
- web整站https环境下使用(spring mvc)redirect重定向到http协议问题
- 超级详细的Java正则表达式----学习学习!
- Cmake-add_executable
- [置顶] LaTex 符号
- 3——虚拟机体验之VirtualBox篇——性能强大的经典架构
- linux下安装postgresql
- lazyload实现原理(图片延迟加载)
- 穷举法解决组合问题
- OpenGL tools and books
- 二叉排序树(面试四)