abstrait:Java多線程實(shí)現(xiàn)方式主要有四種:繼承Thread類、實(shí)現(xiàn)Runnable接口、實(shí)現(xiàn)Callable接口通過FutureTask包裝器來創(chuàng)建Thread線程、使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的多線程。其中前兩種方式線程執(zhí)行完后都沒有返回值,后兩種是帶返回值的。1、繼承Thread類創(chuàng)建線程Thread類本質(zhì)上是實(shí)現(xiàn)了Runnable接口的一個(gè)實(shí)例,代
Java多線程實(shí)現(xiàn)方式主要有四種:繼承Thread類、實(shí)現(xiàn)Runnable接口、實(shí)現(xiàn)Callable接口通過FutureTask包裝器來創(chuàng)建Thread線程、使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的多線程。
其中前兩種方式線程執(zhí)行完后都沒有返回值,后兩種是帶返回值的。
1、繼承Thread類創(chuàng)建線程
Thread類本質(zhì)上是實(shí)現(xiàn)了Runnable接口的一個(gè)實(shí)例,代表一個(gè)線程的實(shí)例。啟動線程的唯一方法就是通過Thread類的start()實(shí)例方法。start()方法是一個(gè)native方法,它將啟動一個(gè)新線程,并執(zhí)行run()方法。這種方式實(shí)現(xiàn)多線程很簡單,通過自己的類直接extend Thread,并復(fù)寫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、實(shí)現(xiàn)Runnable接口創(chuàng)建線程
如果自己的類已經(jīng)extends另一個(gè)類,就無法直接extends Thread,此時(shí),可以實(shí)現(xiàn)一個(gè)Runnable接口,如下:
為了啟動MyThread,需要首先實(shí)例化一個(gè)Thread,并傳入自己的MyThread實(shí)例:
事實(shí)上,當(dāng)傳入一個(gè)Runnable target參數(shù)給Thread后,Thread的run()方法就會調(diào)用target.run(),參考JDK源代碼:
3、實(shí)現(xiàn)Callable接口通過FutureTask包裝器來創(chuàng)建Thread線程
Callable接口(也只有一個(gè)方法)定義如下:
public interface Callable<V> { V call() throws Exception; }
public class SomeCallable<V> extends OtherClass implements Callable<V> { @Override public V call() throws Exception { // TODO Auto-generated method stub return null; } }
Callable<V> oneCallable = new SomeCallable<V>(); //由Callable<Integer>創(chuàng)建一個(gè)FutureTask<Integer>對象: FutureTask<V> oneTask = new FutureTask<V>(oneCallable); //注釋:FutureTask<Integer>是一個(gè)包裝器,它通過接受Callable<Integer>來創(chuàng)建,它同時(shí)實(shí)現(xiàn)了Future和Runnable接口。 //由FutureTask<Integer>創(chuàng)建一個(gè)Thread對象: Thread oneThread = new Thread(oneTask); oneThread.start(); //至此,一個(gè)線程就創(chuàng)建完成了。
4、使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的線程
ExecutorService、Callable、Future三個(gè)接口實(shí)際上都是屬于Executor框架。返回結(jié)果的線程是在JDK1.5中引入的新特征,有了這種特征就不需要再為了得到返回值而大費(fèi)周折了。而且自己實(shí)現(xiàn)了也可能漏洞百出。
可返回值的任務(wù)必須實(shí)現(xiàn)Callable接口。類似的,無返回值的任務(wù)必須實(shí)現(xiàn)Runnable接口。
執(zhí)行Callable任務(wù)后,可以獲取一個(gè)Future的對象,在該對象上調(diào)用get就可以獲取到Callable任務(wù)返回的Object了。
注意:get方法是阻塞的,即:線程無返回結(jié)果,get方法會一直等待。
再結(jié)合線程池接口ExecutorService就可以實(shí)現(xiàn)傳說中有返回結(jié)果的多線程了。
下面提供了一個(gè)完整的有返回結(jié)果的多線程測試?yán)?,在JDK1.5下驗(yàn)證過沒問題可以直接使用。代碼如下:
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("----程序開始運(yùn)行----"); Date date1 = new Date(); int taskSize = 5; // 創(chuàng)建一個(gè)線程池 ExecutorService pool = Executors.newFixedThreadPool(taskSize); // 創(chuàng)建多個(gè)有返回值的任務(wù) List<Future> list = new ArrayList<Future>(); for (int i = 0; i < taskSize; i++) { Callable c = new MyCallable(i + " "); // 執(zhí)行任務(wù)并獲取Future對象 Future f = pool.submit(c); // System.out.println(">>>" + f.get().toString()); list.add(f); } // 關(guān)閉線程池 pool.shutdown(); // 獲取所有并發(fā)任務(wù)的運(yùn)行結(jié)果 for (Future f : list) { // 從Future對象上獲取任務(wù)的返回值,并輸出到控制臺 System.out.println(">>>" + f.get().toString()); } Date date2 = new Date(); System.out.println("----程序結(jié)束運(yùn)行----,程序運(yùn)行時(shí)間【" + (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 + "任務(wù)啟動"); Date dateTmp1 = new Date(); Thread.sleep(1000); Date dateTmp2 = new Date(); long time = dateTmp2.getTime() - dateTmp1.getTime(); System.out.println(">>>" + taskNum + "任務(wù)終止"); return taskNum + "任務(wù)返回運(yùn)行結(jié)果,當(dāng)前任務(wù)時(shí)間【" + time + "毫秒】"; } }
代碼說明:
上述代碼中Executors類,提供了一系列工廠方法用于創(chuàng)建線程池,返回的線程池都實(shí)現(xiàn)了ExecutorService接口。
public static ExecutorService newFixedThreadPool(int nThreads)
創(chuàng)建固定數(shù)目線程的線程池。
public static ExecutorService newCachedThreadPool()
創(chuàng)建一個(gè)可緩存的線程池,調(diào)用execute 將重用以前構(gòu)造的線程(如果線程可用)。如果現(xiàn)有線程沒有可用的,則創(chuàng)建一個(gè)新線程并添加到池中。終止并從緩存中移除那些已有 60 秒鐘未被使用的線程。
public static ExecutorService newSingleThreadExecutor()
創(chuàng)建一個(gè)單線程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
創(chuàng)建一個(gè)支持定時(shí)及周期性的任務(wù)執(zhí)行的線程池,多數(shù)情況下可用來替代Timer類。
ExecutoreService提供了submit()方法,傳遞一個(gè)Callable,或Runnable,返回Future。如果Executor后臺線程池還沒有完成Callable的計(jì)算,這調(diào)用返回Future對象的get()方法,會阻塞直到計(jì)算完成。