Java 中的 Callable 和 Future\n
java.util.concurrent.Callable 物件可以返回由執行緒完成的已計算結果,而 runnable 介面只能執行該執行緒。Callable 物件返回一個 Future 物件,該物件提供方法來監視執行緒執行的任務進度。future 物件可用於檢查 Callable 的狀態,然後在該執行緒完成後從 Callable 中檢索結果。它還提供超時功能。
語法
//submit the callable using ThreadExecutor //and get the result as a Future object Future<Long> result10 = executor.submit(new FactorialService(10)); //get the result using get method of the Future object //get method waits till the thread execution and then return the result of the execution. Long factorial10 = result10.get();
示例
以下 TestThread 程式展示了在基於執行緒的環境中使用 Future 和 Callable。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newSingleThreadExecutor();
System.out.println("Factorial Service called for 10!");
Future<Long> result10 = executor.submit(new FactorialService(10));
System.out.println("Factorial Service called for 20!");
Future<Long> result20 = executor.submit(new FactorialService(20));
Long factorial10 = result10.get();
System.out.println("10! = " + factorial10);
Long factorial20 = result20.get();
System.out.println("20! = " + factorial20);
executor.shutdown();
}
static class FactorialService implements Callable<Long> {
private int number;
public FactorialService(int number) {
this.number = number;
}
@Override
public Long call() throws Exception {
return factorial();
}
private Long factorial() throws InterruptedException {
long result = 1;
while (number != 0) {
result = number * result;
number--;
Thread.sleep(100);
}
return result;
}
}
}將產生以下結果。
輸出
Factorial Service called for 10! Factorial Service called for 20! 10! = 3628800 20! = 2432902008176640000
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP