1. 程式人生 > >單線程與線程池的性能對比

單線程與線程池的性能對比

block execute for try log lsi down blocking exe

親自嘗試了之後才發現,雖然同是一個線程在工作,但是使用線程池效率竟然可以提升這麽多!

代碼如下:

 1 package cn.sp.test;
 2 
 3 import java.util.LinkedList;
 4 import java.util.List;
 5 import java.util.Random;
 6 import java.util.concurrent.LinkedBlockingQueue;
 7 import java.util.concurrent.ThreadPoolExecutor;
 8 import java.util.concurrent.TimeUnit;
9 10 public class MainMethod { 11 public static void main(String[] args) { 12 int count = 200000; 13 useThreadPool(count); 14 //useThread(count); 15 } 16 /** 17 * 使用線程池77ms 18 * @param count 19 */ 20 public static void useThreadPool(int count){ 21 //
開始時間 22 long startTime = System.currentTimeMillis(); 23 //使用不可變類來保存線程安全性 24 final List<Integer> list = new LinkedList<Integer>(); 25 //雖然線程最大數量被限制為1,但是可以重復使用,減少了創建和銷毀線程的開銷 26 int corePoolSize = 1; 27 int
maximumPoolSize = 1; 28 29 ThreadPoolExecutor tp = 30 new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(count)); 31 final Random random = new Random();//使用final 理由同上 32 for(int i = 0 ; i<count ; i++){ 33 tp.execute(new Runnable() { 34 35 @Override 36 public void run() { 37 list.add(random.nextInt()); 38 39 } 40 }); 41 } 42 43 //關閉線程池 44 tp.shutdown(); 45 try { 46 tp.awaitTermination(1, TimeUnit.SECONDS); 47 } catch (InterruptedException e) { 48 // TODO Auto-generated catch block 49 e.printStackTrace(); 50 } 51 //執行時間 52 System.out.println(System.currentTimeMillis() - startTime); 53 System.out.println(list.size()); 54 } 55 /** 56 * 每次創建一個新的線程: 19760ms 57 * @param count 58 */ 59 public static void useThread(int count){ 60 //開始時間 61 long startTime = System.currentTimeMillis(); 62 final List<Integer> list = new LinkedList<Integer>(); 63 final Random random = new Random(); 64 65 for(int i=0 ; i< count ; i++){ 66 Thread thread = new Thread(new Runnable() { 67 68 @Override 69 public void run() { 70 // TODO Auto-generated method stub 71 list.add(random.nextInt()); 72 } 73 }); 74 75 thread.start(); 76 try { 77 thread.join();//被調用後main線程將被一直阻塞,直到該線程執行完畢 78 } catch (InterruptedException e) { 79 // TODO Auto-generated catch block 80 e.printStackTrace(); 81 } 82 } 83 84 //執行時間 85 System.out.println(System.currentTimeMillis() - startTime); 86 System.out.println(list.size()); 87 } 88 }

和我一樣的多線程初學者可以試下。

單線程與線程池的性能對比