您好,登錄后才能下訂單哦!
創(chuàng)建java線程,我們經(jīng)常使用兩種方式:
但這兩種方式有一個缺陷:在執(zhí)行完任務(wù)之后無法直接獲取執(zhí)行結(jié)果。
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("線程執(zhí)行中...");
}
};
Thread thread = new Thread(runnable);
thread.start();
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("線程執(zhí)行中...");
return 100;
}
};
FutureTask < Integer > futureTask = new FutureTask < Integer > (callable);
new Thread(futureTask).start();
// 等待1秒,讓線程執(zhí)行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("獲取執(zhí)行結(jié)果:" + futureTask.get());
}
Callable < Integer > callable = new Callable < Integer > () {
@Override
public Integer call() throws Exception {
System.out.println("線程執(zhí)行中...");
return 100;
}
};
ExecutorService service = Executors.newCachedThreadPool();
Future < Integer > future = service.submit(callable);
// 等待1秒,讓線程執(zhí)行
TimeUnit.SECONDS.sleep(1);
if(futureTask.isDone()) {
System.out.println("獲取執(zhí)行結(jié)果:" + future.get());
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。