三種實現線程的方法
-
繼承Thread類,重寫run方法
-
實現Runnable接口,重寫run方法
-
實現Callable<>接口,重寫call方法,使用FutureTask方式
-
代碼
package day0122;
import org.junit.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @Author Braylon
* @Date 2020/1/22 9:31
*/
public class threeWays {
public static class thread1 extends Thread {
@Override
public void run() {
System.out.println("child thread: extends Thread to realise concurrent");
}
}
public static class thread2 implements Runnable {
public void run() {
System.out.println("child thread2: implements Runnable to realise concurrent");
}
}
public static class thread3 implements Callable<String> {
public String call() throws Exception {
return "this is third method Callable to realize concurrent";
}
}
@Test
public void test() {
// thread1 thread1 = new thread1();
// thread1.start();
//
// thread2 thread2 = new thread2();
// new Thread(thread2).start();
// new Thread(thread2).start();
FutureTask<String> stringfuturetask = new FutureTask<>(new thread3());
new Thread(stringfuturetask).start();
try {
String s = stringfuturetask.get();
System.out.println("thread3: " + s);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
優缺點
- 繼承THread
優點:
使用繼承 的方式方便傳參,可以在子類裏面添加成員變量,通過set方法設置參數或者通過構造函數進行傳遞
缺點:
java不支持多繼承,也就是當繼承了Thread類後不能再繼承其他類。任務與代碼沒有分離,當多個線程執行一樣的任務時需要多個任務代碼。
- 實現Runnable接口
優點:可以繼承其他類,也可以添加參數進行任務分區。
缺點:
這兩種方法都有一個缺點就是任務沒有返回值。
- 使用FutureTask方式
優點:
可以得到任務的返回結果。