實現Callable介面
阿新 • • 發佈:2018-12-10
Java 5.0 在java.util.concurrent 提供了一個新的建立執行執行緒的方式:Callable 介面。
Callable 介面類似於Runnable,兩者都是為那些其例項可能被另一個執行緒執行的類設計的。但是Runnable 不會返回結果,並且無法丟擲經過檢查的異常。
Callable介面示例如下:
public class TestCallable {
public static void main(String[] args){
CallableDemo callableDemo = new CallableDemo();
//執行Callable需要有FutureTask支援,用於接收運算結果
FutureTask<Integer> futureTask = new FutureTask<>(callableDemo);
new Thread(futureTask).start();
try {
//接收執行緒運算後結果
Integer sum = futureTask.get();
System.out.println(sum);
//futureTask.get();執行完才能列印橫線,說明
System.out.println("--------------------------------------" );
}catch (Exception e) {
e.printStackTrace();
}
}
}
class CallableDemo implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int sum=0;
for (int i=0;i<=100;i++){
System.out.println(i);
sum +=i;
}
return sum;
}
}
Callable 需要依賴FutureTask ,FutureTask 也可以用作閉鎖。
如下圖所示,只有獲取到結果後才會列印橫線:
FutureTask擁有方法如下:
其實現了RunnableFuture介面:
public class FutureTask<V> implements RunnableFuture<V> {
//...
}
其中RunnableFuture介面又繼承自Runnable和Future介面:
/**
* A {@link Future} that is {@link Runnable}. Successful execution of
* the {@code run} method causes completion of the {@code Future}
* and allows access to its results.
* @see FutureTask
* @see Executor
* @since 1.6
* @author Doug Lea
* @param <V> The result type returned by this Future's {@code get} method
*/
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
Future是什麼,有什麼用?
檢視其javadoc如下:
/**
* A {@code Future} represents the result of an asynchronous
* computation. Methods are provided to check if the computation is
* complete, to wait for its completion, and to retrieve the result of
* the computation. The result can only be retrieved using method
* {@code get} when the computation has completed, blocking if
* necessary until it is ready. Cancellation is performed by the
* {@code cancel} method. Additional methods are provided to
* determine if the task completed normally or was cancelled. Once a
* computation has completed, the computation cannot be cancelled.
* If you would like to use a {@code Future} for the sake
* of cancellability but not provide a usable result, you can
* declare types of the form {@code Future<?>} and
* return {@code null} as a result of the underlying task.
參考博文: