zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    排查线上问题常用的几个Linux命令
    OAuth2简易实战(一)-四种模式
    程序员必备的网站推荐
    C++ sizeof
    C++ 求余运算符
    C++ mutable(可变的)
    C++ const_cast用法
    C++常变量和文字常量
    C++中 <iso646.h>头文件
    java-网络编程-使用URLDecoder和URLEncoder
  • 原文地址:https://www.cnblogs.com/kumu/p/6639152.html
Copyright © 2011-2022 走看看