Java线程池
2016-05-16 20:55
441 查看
简单实现线程池
Java线程池的分析与使用
import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; /** * Created by wenqing on 2016/5/16. */ public class ThreadPool { //阻塞队列 private BlockingQueue<Runnable> taskQueue; private List<PoolThread> threads; private boolean isStopped = false; public ThreadPool(int threadSize,int runnableSize) { threads = new ArrayList<PoolThread>(threadSize); taskQueue = new LinkedBlockingDeque<Runnable>(runnableSize) ; for(int i = 0;i < threadSize; i++) { PoolThread thread = new PoolThread(taskQueue); threads.add(thread); } for (PoolThread thread : threads) { thread.start(); } } public void execute(Runnable runnable) { if(isStopped) throw new IllegalStateException("ThreadPool is stopped"); taskQueue.add(runnable); } public void stop() { if(!isStopped) { isStopped = true; for (PoolThread thread : threads) { thread.toStop(); } } } } class PoolThread extends Thread { private BlockingQueue<Runnable> taskQueue; private boolean isStoped = false; public PoolThread(BlockingQueue<Runnable> taskQueue) { this.taskQueue = taskQueue; } @Override public void run() { while (!isStoped) { try { Runnable runnable = taskQueue.take(); runnable.run(); } catch (InterruptedException e) { // 写日志或者报告异常, // 但保持线程池运行. } } } public void toStop() { isStoped = true; this.interrupt(); } public boolean isStoped() { return isStoped; } }
相关文章推荐
- java8 构造日期时间
- Java 并发:Executors 和线程池(不错)
- 关于使用Struts2框架的校验文件不起作用的原因分析
- java中hashcode()和equals()方法
- JavaWeb实现简单的文件上传下载
- Codeforces 66A:Petya and Java(水题)
- JAVA IO——对象序列化解析及项目实战
- 作业_java基础第八天_多线程
- java 垃圾回收器的清楚
- java CountDownLatch测试并发数
- Java annotation
- Eclipse调试Bug的七种常用技巧
- Java中equals和==的区别
- Java出现No enclosing instance of type E is accessible
- 【Java】多线程实现方式
- java布局总结
- 【JDK】:Fork-Join框架
- java 学习曲线(Java学习书籍推荐)
- Java开发中的23种设计模式详解
- JAVA设计模式之单例模式