使用線程池和不使用線程池的區別


目的:隨機產生一個整數並加入到一個隊列中。

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總結:

  差異在於使用線程池的方式是復用線程,不使用線程池的方式是每次都要創建線程。所以消耗的時間差距大,因為執行的工作比較簡單所以大部分時間用來創建線程。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM