Java多線程實現的三種方式
Java多線程實現方式主要有三種:繼承Thread類、實現Runnable接口、使用ExecutorService、Callable、Future實現有返回結果的多線程。其中前兩種方式線程執(zhí)行完后都沒有返回值,只有最后一種是帶返回值的。
1、繼承Thread類實現多線程
繼承Thread類的方法盡管被我列為一種多線程實現方式,但Thread本質上也是實現了Runnable接口的一個實例,它代表一個線程的實例,并且,啟動線程的唯一方法就是通過Thread類的start()實例方法。start()方法是一個native方法,它將啟動一個新線程,并執(zhí)行run()方法。這種方式實現多線程很簡單,通過自己的類直接extend Thread,并復寫run()方法,就可以啟動新線程并執(zhí)行自己定義的run()方法。例如:
- public class MyThread extends Thread {
 - public void run() {
 - System.out.println("MyThread.run()");
 - }
 - }
 
在合適的地方啟動線程如下:
- MyThread myThread1 = new MyThread();
 - MyThread myThread2 = new MyThread();
 - myThread1.start();
 - myThread2.start();
 
2、實現Runnable接口方式實現多線程
如果自己的類已經extends另一個類,就無法直接extends Thread,此時,必須實現一個Runnable接口,如下:
- public class MyThread extends OtherClass implements Runnable {
 - public void run() {
 - System.out.println("MyThread.run()");
 - }
 - }
 
為了啟動MyThread,需要首先實例化一個Thread,并傳入自己的MyThread實例:
- MyThread myThread = new MyThread();
 - Thread thread = new Thread(myThread);
 - thread.start();
 
事實上,當傳入一個Runnable target參數給Thread后,Thread的run()方法就會調用target.run(),參考JDK源代碼:
- public void run() {
 - if (target != null) {
 - target.run();
 - }
 - }
 
3、使用ExecutorService、Callable、Future實現有返回結果的多線程
ExecutorService、Callable、Future這個對象實際上都是屬于Executor框架中的功能類。想要詳細了解Executor框架的可以訪問http://www.javaeye.com/topic/366591 ,這里面對該框架做了很詳細的解釋。返回結果的線程是在JDK1.5中引入的新特征,確實很實用,有了這種特征我就不需要再為了得到返回值而大費周折了,而且即便實現了也可能漏洞百出。
可返回值的任務必須實現Callable接口,類似的,無返回值的任務必須Runnable接口。執(zhí)行Callable任務后,可以獲取一個Future的對象,在該對象上調用get就可以獲取到Callable任務返回的Object了,再結合線程池接口ExecutorService就可以實現傳說中有返回結果的多線程了。下面提供了一個完整的有返回結果的多線程測試例子,在JDK1.5下驗證過沒問題可以直接使用。代碼如下:
- import java.util.concurrent.*;
 - import java.util.Date;
 - import java.util.List;
 - import java.util.ArrayList;
 - /**
 - * 有返回值的線程
 - */
 - @SuppressWarnings("unchecked")
 - public class Test {
 - public static void main(String[] args) throws ExecutionException,
 - InterruptedException {
 - System.out.println("----程序開始運行----");
 - Date date1 = new Date();
 - int taskSize = 5;
 - // 創(chuàng)建一個線程池
 - ExecutorService pool = Executors.newFixedThreadPool(taskSize);
 - // 創(chuàng)建多個有返回值的任務
 - List<Future> list = new ArrayList<Future>();
 - for (int i = 0; i < taskSize; i++) {
 - Callable c = new MyCallable(i + " ");
 - // 執(zhí)行任務并獲取Future對象
 - Future f = pool.submit(c);
 - // System.out.println(">>>" + f.get().toString());
 - list.add(f);
 - }
 - // 關閉線程池
 - pool.shutdown();
 - // 獲取所有并發(fā)任務的運行結果
 - for (Future f : list) {
 - // 從Future對象上獲取任務的返回值,并輸出到控制臺
 - System.out.println(">>>" + f.get().toString());
 - }
 - Date date2 = new Date();
 - System.out.println("----程序結束運行----,程序運行時間【"
 - + (date2.getTime() - date1.getTime()) + "毫秒】");
 - }
 - }
 - class MyCallable implements Callable<Object> {
 - private String taskNum;
 - MyCallable(String taskNum) {
 - this.taskNum = taskNum;
 - }
 - public Object call() throws Exception {
 - System.out.println(">>>" + taskNum + "任務啟動");
 - Date dateTmp1 = new Date();
 - Thread.sleep(1000);
 - Date dateTmp2 = new Date();
 - long time = dateTmp2.getTime() - dateTmp1.getTime();
 - System.out.println(">>>" + taskNum + "任務終止");
 - return taskNum + "任務返回運行結果,當前任務時間【" + time + "毫秒】";
 - }
 - }
 
代碼說明:
上述代碼中Executors類,提供了一系列工廠方法用于創(chuàng)先線程池,返回的線程池都實現了ExecutorService接口。
public static ExecutorService newFixedThreadPool(int nThreads) 創(chuàng)建固定數目線程的線程池。
public static ExecutorService newCachedThreadPool() 創(chuàng)建一個可緩存的線程池,調用execute 將重用以前構造的線程(如果線程可用)。如果現有線程沒有可用的,則創(chuàng)建一個新線程并添加到池中。終止并從緩存中移除那些已有 60 秒鐘未被使用的線程。
public static ExecutorService newSingleThreadExecutor() 創(chuàng)建一個單線程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 創(chuàng)建一個支持定時及周期性的任務執(zhí)行的線程池,多數情況下可用來替代Timer類。
ExecutoreService提供了submit()方法,傳遞一個Callable,或Runnable,返回Future。如果Executor后臺線程池還沒有完成Callable的計算,這調用返回Future對象的get()方法,會阻塞直到計算完成。















 
 
 











 
 
 
 