原文链接:
对newCachedThreadPool回收线程的证明
public class test{ public static void main(String[] args) { ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int index = i;// try {// Thread.sleep(index * 1000);// } catch (InterruptedException e) {// e.printStackTrace();// } cachedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(index+" "+Thread.currentThread().getName()+" "+Thread.currentThread().hashCode()); } }); } }}
结果只是产生九个不同的线程
2 pool-1-thread-3 1176331429
5 pool-1-thread-6 5734013053 pool-1-thread-4 2273095141 pool-1-thread-2 4071599796 pool-1-thread-7 8604951017 pool-1-thread-8 1850844170 pool-1-thread-1 14088994344 pool-1-thread-5 7755931378 pool-1-thread-9 5988370079 pool-1-thread-2 407159979
二次测试,只有5个
0 pool-1-thread-1 2087961100
2 pool-1-thread-3 17944192191 pool-1-thread-2 20167116534 pool-1-thread-1 20879611006 pool-1-thread-3 17944192195 pool-1-thread-2 20167116539 pool-1-thread-3 17944192198 pool-1-thread-2 20167116537 pool-1-thread-5 14443827733 pool-1-thread-4 847094661
三次测试,有6个
0 pool-1-thread-1 461277103
2 pool-1-thread-3 20167116534 pool-1-thread-5 8470946613 pool-1-thread-4 17944192196 pool-1-thread-4 17944192197 pool-1-thread-5 8470946618 pool-1-thread-1 4612771035 pool-1-thread-3 20167116531 pool-1-thread-2 20879611009 pool-1-thread-6 1287333624
如果把中间休眠的注释去掉,效果更加明显,只有一个线程
0 pool-1-thread-1 2016711653
1 pool-1-thread-1 20167116532 pool-1-thread-1 20167116533 pool-1-thread-1 20167116534 pool-1-thread-1 20167116535 pool-1-thread-1 20167116536 pool-1-thread-1 20167116537 pool-1-thread-1 20167116538 pool-1-thread-1 20167116539 pool-1-thread-1 2016711653