使用线程池和不使用线程池的区别

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

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://www.cnblogs.com/LuoPengSdok/p/11453359.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值