Java 中的物件透過new 建立實體物件,如果建立大量短生命週期的物件,使用new的效能將會非常差,為解決此問題可以使用池化技術。
Java 執行續池( Thread Pool ) 範例如下 :
首先需要先建立一個生命週期短暫的執行續:
1 2 3 4 5 6 7 8 9 10 11 |
public class TempThread implements Runnable{ private int id = 0; @Override public void run() { // TODO Auto-generated method stub id++; } } |
然後透過以下程式測試使用Thread Pool 與 一般new 方法的效能差異:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class ThreadPoolTest { public static void main(String[] args) { final int THREAD_COUNT = 1000; Runtime runtime = Runtime.getRuntime(); runtime.gc(); //執行垃圾回收器,可以減少誤差 long freeMemory = runtime.freeMemory(); long currentTime = System.currentTimeMillis(); for(int i=0;i<THREAD_COUNT;i++) new Thread(new TempThread()).start(); System.out.println("建立 "+THREAD_COUNT+"個執行緒,所佔用記憶體 \t" + (freeMemory - runtime.freeMemory()) + " bits"); System.out.println("建立 "+THREAD_COUNT+"個執行緒,所消耗時間\t" + (System.currentTimeMillis() - currentTime) + " ms"); runtime.gc(); freeMemory = runtime.freeMemory(); currentTime = System.currentTimeMillis(); ExecutorService executorService = Executors.newFixedThreadPool(2); for(int i=0;i<THREAD_COUNT;i++) executorService.submit(new TempThread()); System.out.println("POOL "+THREAD_COUNT+"個執行緒,所佔用記憶體 \t" + (freeMemory - runtime.freeMemory())+ " bits"); System.out.println("POOL "+THREAD_COUNT+"個執行緒,所消耗時間\t" + (System.currentTimeMillis() - currentTime) + " ms"); executorService.shutdownNow(); } } |
實驗成果如下,從下圖中可以發現,使用POOL建立執行續的速度快非常多。
原理 :
一個Thread Pool 有多個處於 可執行 狀態的Thread ,當Thread Poolhread Pool中增加含有 Runnable 或 Callable 介面的物件時,就會有一個Thread來執行run()或call()方法,如果方法執行完畢,該執行續並不會終止,而是會繼續待在Thread Pool中處於可執行狀態、以執行新的工作。
完整專案(連結)
文章標籤
全站熱搜