java的多執行緒學習,第一記
阿新 • • 發佈:2018-11-28
實現多執行緒有三種方法
1,繼承THread類
import com.sun.org.apache.xpath.internal.SourceTree; public class test{ //繼承Thread類並重寫run方法 public static class MyThread extends Thread{ @Override public void run(){ System.out.println("I am a child thread"); } } public static void main(String[] args) { //建立執行緒 MyThread thread = new MyThread(); //啟動執行緒 thread.start(); } }
2,實現Runable介面
public class test1{ public static class RunableTask implements Runnable{ @Override public void run(){ System.out.println("I am a child thread"); } } public static void main(String[] args) { RunableTask task = new RunableTask(); new Thread(task).start(); new Thread(task).start(); } }
3,使用FutrueTask方法
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class test2{ public static class CallerTask implements Callable<String>{ @Override public String call()throws Exception{ return "hello"; } } public static void main(String[] args) { //create asynchronous task FutureTask<String> futureTask = new FutureTask<>(new CallerTask()); //start thread new Thread(futureTask).start(); try { //wait task excute String result = futureTask.get(); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } }
三種方式的對比優劣:
使用繼承方式的好處是,在run()方法內獲取當前執行緒直接使用this就可以了,無須使用Thread.currentThread()方法,不好的地方是Java不支援多執行緒,如果繼承了Thread類,
那麼就不能繼承其他類了。另外任務與程式碼沒有分離,當多個執行緒執行一樣的任務時需
要多份任務程式碼,而Runable介面則沒有這個限制。
如上面程式碼所示,兩個執行緒共用一個task程式碼邏輯,如果需要,可以給RunableTask新增引數
進行任務區分。但是上面兩種方式都有一個缺點,就是任務沒有返回值。用FutureTask方式是有返回值的