Java多线程-线程池

原文链接:Java(Android)线程池

对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 573401305
3 pool-1-thread-4 227309514
1 pool-1-thread-2 407159979
6 pool-1-thread-7 860495101
7 pool-1-thread-8 185084417
0 pool-1-thread-1 1408899434
4 pool-1-thread-5 775593137
8 pool-1-thread-9 598837007
9 pool-1-thread-2 407159979

二次测试,只有5个

0 pool-1-thread-1 2087961100
2 pool-1-thread-3 1794419219
1 pool-1-thread-2 2016711653
4 pool-1-thread-1 2087961100
6 pool-1-thread-3 1794419219
5 pool-1-thread-2 2016711653
9 pool-1-thread-3 1794419219
8 pool-1-thread-2 2016711653
7 pool-1-thread-5 1444382773
3 pool-1-thread-4 847094661

三次测试,有6个

0 pool-1-thread-1 461277103
2 pool-1-thread-3 2016711653
4 pool-1-thread-5 847094661
3 pool-1-thread-4 1794419219
6 pool-1-thread-4 1794419219
7 pool-1-thread-5 847094661
8 pool-1-thread-1 461277103
5 pool-1-thread-3 2016711653
1 pool-1-thread-2 2087961100
9 pool-1-thread-6 1287333624

 

如果把中间休眠的注释去掉,效果更加明显,只有一个线程

0 pool-1-thread-1 2016711653
1 pool-1-thread-1 2016711653
2 pool-1-thread-1 2016711653
3 pool-1-thread-1 2016711653
4 pool-1-thread-1 2016711653
5 pool-1-thread-1 2016711653
6 pool-1-thread-1 2016711653
7 pool-1-thread-1 2016711653
8 pool-1-thread-1 2016711653
9 pool-1-thread-1 2016711653

 

posted @ 2017-03-29 12:21  枯木fc  阅读(187)  评论(2编辑  收藏  举报