Callable和Runnable用法和比較

2021-07-31 07:25:45 字數 896 閱讀 3100

比較:

callable有返回值並且可以拋異常;

runnable無返回值並且不能拋異常。

futuretask和future:

future:

介面,用於獲得任務的執行結果。

future的get方法獲取結果只有在計算完成時獲取,否則會一直阻塞直到任務轉入完成狀態,然後會返回結果或者丟擲異常。

futuretask:

實現類,實現了runnablefuture介面,而runnablefuture同時繼承runnable和future介面,即futuretask是runnable和future的實現類。

可使用futuretask包裝callable或runnable物件。

使用方法:

(1)runnable task = new runnabletask();

new thread(task).start();

callable task = new callabletask();

futuretask futuretask = new futuretask(task);

new thread(futuretask ).start();

...futuretask.get();

(2)executorservice pool = executors.newcachedthreadpool();

runnable task = new runnabletask();

pool.execute(task);

callabletask = new callabletask();

futurefuture = pool.submit(task);

...future.get();

推薦優先使用第二種方法。

Callable和future介面詳解

runnbale封裝乙個非同步執行的任務,可以把它想象成乙個沒有任何引數和返回值的非同步方法。callable和runnable相似,但是它有返回值。callable介面是引數化的型別,只有乙個方法call public inte ce callable catch runtimeexception...

Java執行緒 Callable和Future

public class callableandfuture futuretaskfuture new futuretask callable new thread future start try catch interruptedexception e catch executionexcept...

Java執行緒 Callable和Future

public class callableandfuture futuretaskfuture new futuretask callable new thread future start try catch interruptedexception e catch executionexcept...