生产线程(控制同时运行线程总量)

用处:多线程编程中,限制线程的总数量。

 

使用方式:

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() ; 
            }
        }
    }

}

 

posted @ 2014-07-11 15:15  行-云  阅读(262)  评论(0)    收藏  举报