生产线程(控制同时运行线程总量)
2014-07-11 15:15
274 查看
用处:多线程编程中,限制线程的总数量。
使用方式:
Runnable runnable = 一个实现了Runnable接口的对象 ;
ProductThread pt = ThreadProducer.instance().getThread(runnable) ;
pt.start() ;
ProductThread.java
ThreadProducer.java
使用方式:
Runnable runnable = 一个实现了Runnable接口的对象 ;
ProductThread pt = ThreadProducer.instance().getThread(runnable) ;
pt.start() ;
ProductThread.java
package net.xy.timer; /** * 线程 * @author ooi * */ public class ProductThread extends Thread{ public ProductThread(Runnable runnable){ super(runnable) ; } public void run(){ super.run() ; //收尾 ThreadProducer.instance().remove(this) ; } }
ThreadProducer.java
package net.xy.timer; import java.util.ArrayList; import java.util.List; /** * 线程生成者 * 生产方式:有需求则生产 * 限制:同时处于使用中的线程只能有N个 * 如果当前不可生成,则进入等待状态,直到到达可以生产条件 * @author ooi * */ public class ThreadProducer { //单例 private static ThreadProducer m = null ; private ThreadProducer(){ init() ; } public static ThreadProducer instance(){ if( m == null ){ m = new ThreadProducer() ; } return m ; } /** * 同时处于使用中的线程最多能有几个 */ public static final int MAX_COUNT = 16 ; /** * 所有没有使用结束的线程 */ private List<ProductThread> productThreadList ; /** * 获取线程总数 */ public int getThreadCount(){ synchronized (productThreadList) { System.out.println(productThreadList.size()); return productThreadList.size() ; } } /** * 初始化 */ private void init(){ productThreadList = new ArrayList<ProductThread>() ; } /** * 生成一个线程<br> * 如果当前不可生成,则进入等待状态,直到到达可以生产条件 */ public ProductThread getThread(Runnable runnable){ //判断限制条件 if( getThreadCount() >= MAX_COUNT ){ synchronized (this) { try { this.wait() ; } catch (InterruptedException e) { e.printStackTrace(); } } } //生成线程 ProductThread productThread = new ProductThread(runnable) ; synchronized (productThreadList) { productThreadList.add(productThread) ; } return productThread ; } /** * 移除使用结束的线程(一定要移除) * @param productThread */ public void remove(ProductThread productThread){ synchronized (productThreadList) { productThreadList.remove(productThread) ; } if( getThreadCount() < MAX_COUNT ){ synchronized (this) { this.notify() ; } } } }
相关文章推荐
- 线程工具类(根据电脑逻辑处理器个数控制同时运行的线程个数)
- VC++基础 使用全局变量控制线程运行
- VC++基础 使用全局变量控制线程运行
- 建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC
- 建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC。
- 两个线程同时运行案例
- 不用挂钩绕过 Klister 0.4 ——运行一个自己控制的线程调度程序
- java线程池:获取运行线程数并控制线程启动速度的方法
- JAVA基础学习--一个线程加一运算,一个线程做减一运算,多个线程同时交替运行--synchronized
- 一个线程加一运算,一个线程做减一运算,多个线程同时交替运行--synchronized
- C# 执行固定个数任务自行控制进入线程池的线程数量,多任务同时但是并发数据限定
- 多线程学习之限制同时运行的线程数量
- 通过set和waitOne来控制子线程的运行和停止
- 一种控制线程运行和停止的方法
- Java 并发编程中的 CountDownLatch 锁用于多个线程同时开始运行或主线程等待子线程结束
- 写程序 控制cpu占用率-4 绘制CPU使用率的正弦曲线2 通过C#指定线程运行的 CPU
- 建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC。
- 两个线程同时运行的案例
- 建立m个线程,每个线程只能打印一种字符,要求纯种同时运行,交替打印n次字符
- 线程工具类-通过信号量、计时器等机制控制多线程之间的运行阻塞-笔记整理11