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