zoukankan      html  css  js  c++  java
  • 使用线程池和不使用线程池的区别

    目的:随机产生一个整数并加入到一个队列中。

    1.使用线程池:

     long startTime=System.currentMillis();

     final List<Integer> l=new LinkedList<Integer>();

     ThreadPoolExecutor tp=new ThreadPoolExecutor(1,1,60,TimrUnit,SECONDS,new LinkedBlockingQueue<Runnable>(count));

     final Random random=new Random();

     for(int i=0;i<count;i++){

       tp.executor(new Runnable(){

        @Override

        Public void run(){

          l.add(random.nextInt());

        }

      });

      }

    tp.shutdown();

    try(){

      tp.awaitTermination(1,TimeUnit.DAYS);

    }catch(InterruptedException e){

      e.printStactTrace();

    }

    System.out.println(System.currentTimeMillis()-startTime);

    System.out.println(l.size());

    2.不使用线程池

    long startTime=System.currentMillis();
    final List<Integer> l=new LinkedList<Integer>();

    final Random random=new Random();

     for(int i=0;i<count;i++){

       Thread thread=new Thread(){

        @Override

        Public void run(){

          l.add(random.nextInt());

        }

      });

      thread.start();

      try{

       thread.join(); 

      }catch(InterruptedException e){

        e.printStackTrace();

      }

      }

    System.out.println(System.currentTimeMillis()-startTime);

    System.out.println(l.size);

    3总结:

      差异在于使用线程池的方式是复用线程,不使用线程池的方式是每次都要创建线程。所以消耗的时间差距大,因为执行的工作比较简单所以大部分时间用来创建线程。

  • 相关阅读:
    HTTPS
    数字签名与数字证书
    oracle 10g 数据库与客户端冲突导致实例创建无监听问题
    javascript正则表达式提取子匹配项
    设计模式的分类
    【2020第一篇】环境问题基础知识
    【致 2020】2020
    【python】写demo 的时候,pycharm 编辑器总是提示"method XX may be static"
    sql 练习题 (二)
    【python项目】json 和dict 的区别
  • 原文地址:https://www.cnblogs.com/LuoPengSdok/p/11453359.html
Copyright © 2011-2022 走看看