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

  • 相关阅读:
    Hadoop 2.7 伪分布式环境搭建
    Linux 安装配置 Tomcat
    Hadoop hdfs完全分布式搭建教程
    Hadoop中ssh+IP、ssh+别名免秘钥登录配置
    VMware 克隆多台Linux机器并配置IP
    Linux 安装JDK
    连表更新数据
    设置让php能够以root权限来执行exec() 或者 shell_exec()
    Jsonp 关键字详解及json和jsonp的区别,ajax和jsonp的区别
    php7安装mongoDB扩展
  • 原文地址:https://www.cnblogs.com/kumu/p/6639152.html
Copyright © 2011-2022 走看看