线程池的简单实现Demo

package javatuning.ch4.threadpool.simple;

import java.util.List;
import java.util.Vector;

public class ThreadPool 
{
    private static ThreadPool instance = null;

    //空闲的线程队列
    private List<PThread> idleThreads;
    //已有的线程总数
    private int threadCounter;
    private boolean isShutDown = false;
    
    private ThreadPool() 
    {       
        this.idleThreads = new Vector(5);
        threadCounter = 0;
    }
    
    public int getCreatedThreadsCount() {
        return threadCounter;
    }
    
    //取得线程池的实例
    public synchronized static ThreadPool getInstance() {
        if (instance == null)
            instance = new ThreadPool();
        return instance;
    }
   
    //将线程放入池中
    protected synchronized void repool(PThread repoolingThread)
    {
        if (!isShutDown) 
        {
            idleThreads.add(repoolingThread);
        }
        else 
        {
            repoolingThread.shutDown();//关闭线程
        }
    }
        
    //停止池中所有线程
    public synchronized void shutdown()
    {
       isShutDown = true;
       for (int threadIndex = 0; threadIndex < idleThreads.size(); threadIndex++)
       {
             PThread idleThread = (PThread) idleThreads.get(threadIndex);
             idleThread.shutDown();
       }
    }
    
    //执行任务
    public synchronized void start(Runnable target)
    {
        PThread thread = null; 
        //如果有空闲线程,则直接使用
        if (idleThreads.size() > 0) 
        {
            int lastIndex = idleThreads.size() - 1;
            thread = (PThread) idleThreads.get(lastIndex);
            idleThreads.remove(lastIndex);
            //立即执行这个任务
            thread.setTarget(target);
        }
        //没有空闲线程,则创建新线程
        else 
        { 
            threadCounter++;
            // 创建新线程,
            thread = new PThread(target, "PThread #" + threadCounter, this);
            //启动这个线程
            thread.start();
        }
    }
}


package javatuning.ch4.threadpool.simple;

public class PThread extends Thread 
{
	//线程池
    private ThreadPool pool;
    //任务
    private Runnable target;   
    private boolean isShutDown = false;
    private boolean isIdle = false;
    
    public PThread(Runnable target, String name, ThreadPool pool)
    {
        super(name);
        this.pool = pool;
        this.target = target;
    }
    
    public Runnable getTarget() 
    {
        return target;
    }
    
    public boolean isIdle() 
    {
        return isIdle;
    }
    public void run() 
    {
        while (!isShutDown) 
        {  
            isIdle = false;
            if (target != null) 
            {
            	// 运行任务
                target.run();  
            }
            //任务结束了
            isIdle = true;
            try 
            {
            	//该任务结束后,不关闭线程,而是放入线程池空闲队列
                pool.repool(this);
                synchronized (this) 
                {
                	//线程空闲,等待新的任务到来
                    wait();
                }
            }
            catch (InterruptedException ie)
            {
            }
            isIdle = false;
        }
    }
    
    
    public synchronized void setTarget(java.lang.Runnable newTarget) 
    {
        target = newTarget; 
        notifyAll();       
    }
    
    public synchronized void shutDown()
    {
        isShutDown = true;
        notifyAll();
    }
}


package javatuning.ch4.threadpool.simple;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.junit.Test;

/**
 * 使用简单线程池和直接开启线程的差别
 * @author Administrator
 *
 */
public class TestThreadPool {
	public class MyThread implements Runnable{
		protected String name;
		public MyThread(){
		}
		public MyThread(String name){
			this.name=name;
		}
		@Override
		public void run() {
			try {
				Thread.sleep(100);
				//System.out.print(name+" ");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	@Test
	public void testThreadPool() throws InterruptedException {
		long starttime=System.currentTimeMillis();
		for(int i=0;i<1000;i++){
			ThreadPool.getInstance().start(new MyThread("testThreadPool"+Integer.toString(i)));
		}
		
		long endtime=System.currentTimeMillis();
		System.out.println("testThreadPool"+": "+(endtime-starttime));
		System.out.println("getCreatedThreadsCount:"+ThreadPool.getInstance().getCreatedThreadsCount());
		Thread.sleep(1000);
	}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值