您好,登錄后才能下訂單哦!
創建java線程,我們經常使用兩種方式:
但這兩種方式有一個缺陷:在執行完任務之后無法直接獲取執行結果。
public interface Callable<V> {
V call() throws Exception;
}
public interface Runnable {
public abstract void run();
}
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("線程執行中...");
}
};
Thread thread = new Thread(runnable);
thread.start();
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("線程執行中...");
return 100;
}
};
FutureTask < Integer > futureTask = new FutureTask < Integer > (callable);
new Thread(futureTask).start();
// 等待1秒,讓線程執行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("獲取執行結果:" + futureTask.get());
}
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("線程執行中...");
return 100;
}
};
ExecutorService service = Executors.newCachedThreadPool();
Future < Integer > future = service.submit(callable);
// 等待1秒,讓線程執行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("獲取執行結果:" + future.get());
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。