創建線程的4種方式是什麼?

1 繼承Thread類:本質實現了Runnable接口,調用start()方法開啓新線程,並執行run()方法。

2 實現Runnable接口
3 使用Callable接口創建線程返回值
執行 Callable 任務後,可以獲取一個 Future 的對象,在該對象上調用 get 就可以獲取到 Callable 任務返回的 Object 了,再結合線程池接口 ExecutorService 就可以實現傳說中有返回結果的多線程了。

public class TestCallable {
public static void main(String[] args) {
Thread1Demo td = new Thread1Demo();
//1.執行 Callable 方式,需要 FutureTask 實現類的支持,用於接收運算結果。
FutureTask task = new FutureTask<>(td);
new Thread(task).start();
try {//2.接收線程運算後的結果
if (!task.isDone()) {
System.out.println(“task has not finished, please wait!”);
}
Integer sum = task.get(); //FutureTask 可用於 閉鎖
System.out.println(“task return: -----” + sum);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
class Thread1Demo implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100000; i++) { sum += i; }
return sum;
}
}

4 基於線程池的方式有返回值
不用每次都創建線程,使用Executor創建線程池,向其中加入任務。

public class ThreadPoolDemo {
public static void main(String[] args) {
//創建線程池
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
//向線程池提交任務
Future future = newCachedThreadPool.submit(new MyCallable());
if (!future.isDone()) {
System.out.println(“task has not finished, please wait!”);
}
try {
System.out.println(future.get());
} catch (Exception e) {
e.printStackTrace();
} finally {
newCachedThreadPool.shutdown();
}
}
}
class MyCallable implements Callable {
@Override
public String call() throws Exception {
String value = “test”;
Thread.currentThread().sleep(5000);
return value;
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章