這裡示範了普通線程池以及帶有傳回值的線程池的使用方式
package com.jadyer.thread.pool;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.CompletionService;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorCompletionService;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;/** * ThreadPool Test * @see ================================================================================================ * @see 線程與進程的區別 * @see 1)多個進程的內部資料和狀態是完全獨立的,而多線程則會共用一塊記憶體空間和一組系統資源,有可能互相影響 * @see 2)線程本身的資料通常只有寄存器資料,以及一個程式執行時使用的堆棧。所以線程的切換比進程切換的負擔要小 * @see ================================================================================================ * @see 線程的啟動方式和消亡 * @see 1)以Thread.start()啟動時,JVM會以線程的方式運行它。start()首先會為線程的執行準備系統資源,然後才去調用run方法 * @see 2)以Thread.run()啟動時,JVM會以普通方法運行它。此時就不會存線上程所特有的交替執行的效果 * @see 3)一個線程類的兩個對象,同時以start()方式運行時,JVM仍會把它們當作兩個線程類來執行 * @see 4)終止線程時,絕對不能使用stop()方法,而應該讓run()自然結束 * @see ================================================================================================ * @author 宏宇 * @create Feb 29, 2012 1:13:43 AM */public class ThreadPoolTest {public static void main(String[] args) {new ThreadPoolTest().threadPoolTest();new ThreadPoolTest().threadPoolScheduledTest();new ThreadPoolTest().threadPoolCallbaleAndFutureSignTest();new ThreadPoolTest().threadPoolCallbaleAndFutureMoreTest();}/** * 建立線程池的幾種方式 * @see Executors.newFixedThreadPool(3); //建立固定大小的線程池 * @see Executors.newCachedThreadPool(); //建立緩衝線程池。它會根據實際請求的線程數量動態建立線程 * @see Executors.newSingleThreadExecutor(); //建立單個線程池。它可以實現線程死掉後重新啟動的效果,但實際啟動的是"替補線程" */public void threadPoolTest(){//newSingleThreadExecutor()的好處就是,若池中的線程死了,它會把一個"替補的線程"扶上位,即它會保證池中始終有一個線程存在ExecutorService threadPool = Executors.newSingleThreadExecutor();for(int i=1; i<=10; i++) {final int task = i;threadPool.execute(new MyThread(task)); //注意execute()的傳回值是void}System.out.println("all of 10 tasks have committed......");//線程池中的任務均執行完畢後,關閉線程池threadPool.shutdown();}/** * 線程池啟動定時器 * @see Executors.newScheduledThreadPool(3).schedule(); //建立並執行在給定延遲後啟用的一次性操作 * @see Executors.newScheduledThreadPool(3).scheduleAtFixedRate(); //初次開機後,以固定的頻率自動執行操作 * @see scheduleAtFixedRate()支援間隔重複任務的定時方式,但不直接支援絕對定時方式,我們需要轉換為相對時間的方式,來執行 */public void threadPoolScheduledTest(){//10秒後自動執行一次//Executors.newScheduledThreadPool(3).schedule(new MyScheduledThread(), 10, TimeUnit.SECONDS);//6秒後首次執行,之後每2秒均自動執行一次Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new MyScheduledThread(), 6, 2, TimeUnit.SECONDS);}/** * 線程池返回一個任務的值 * @see 注意:這裡需使用java.util.concurrent.ExecutorService.submit()來提交,它會返回Future對象 * @see 注意:Future取得的結果類型,與Callable返回的結果類型,必須一致。我們這裡是通過泛型來實現的 */public void threadPoolCallbaleAndFutureSignTest(){ExecutorService threadPool = Executors.newSingleThreadExecutor();Future<String> future = threadPool.submit(new Callable<String>() {@Overridepublic String call() throws Exception {Thread.sleep(2000);return "張起靈";};});System.out.println("等待結果");try {System.out.println("拿到結果:" + future.get()); //future.get(4, TimeUnit.SECONDS)} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}/** * 線程池返回多個任務的值 * @see java.util.concurrent.CompletionService用於提交一組Callable任務 * @see CompletionService.take()會返回已完成的一個Callable任務所對應的Future對象 * @see 這就好比同時種植了幾塊菜地,然後等待收菜。收菜時,哪塊菜熟了,就先去收哪塊菜地的菜 */public void threadPoolCallbaleAndFutureMoreTest(){ExecutorService threadPool = Executors.newFixedThreadPool(5);CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool);for(int i=1; i<=5; i++){final int taskCode = i;completionService.submit(new Callable<Integer>(){@Overridepublic Integer call() throws Exception {Thread.sleep(new Random().nextInt(5000));return taskCode;}});}for(int i=0; i<5; i++){try {System.out.println(completionService.take().get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}}}class MyThread implements Runnable{private Integer task;public MyThread(Integer task){this.task = task;}@Overridepublic void run() {//這裡不需要寫成j,因為它和threadPoolTest()裡面的for()迴圈中的i並不是同一個方法中的變數,故其不會衝突for(int i=1; i<=10; i++) {try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " is looping of " + i + " for task of " + task);}}}class MyScheduledThread implements Runnable{@Overridepublic void run() {System.out.println("bombing......");}}