看JAVA编程思想时候感觉作者有句话不对(关于并发)
中文第四版的哦(p657倒数第十行)“然后在它回收旧线程时停止创建新线程”。
这个它指的是CachedThreadPool,我一开始是深信不疑的,认为CachedThreadPool如果一个线程死亡了,那它就不会再创建新的线程了。后来看到一个大牛说“会”。于是自己做了实验:
package test;import java.util.*;import java.util.concurrent.*;import java.util.concurrent.locks.*;import java.io.*;public class Test1 implements Callable<Thread>{static ThreadLocal<Integer> t=new ThreadLocal<Integer>(){@Overrideprotected synchronized Integer initialValue(){return new Integer(0);}};static int count=0;final int id=count++;public Test1(){System.out.println("Constructor:"+id);}static class Test2 implements Runnable{public void run(){System.out.println(t.get()+" o");}}public Thread call(){t.set(id);System.out.println(t.get());return Thread.currentThread();}public static void main(String[] args){ExecutorService exec=Executors.newCachedThreadPool();for (int i=0;i<4;i++)exec.submit(new Test1());Future<Thread> f=exec.submit(new Test1());try{((Thread)f.get()).join();}//等待线程死亡catch (Exception e){}for (int i=0;i<5;i++)exec.execute(new Test2());exec.shutdownNow();}}