菜單
新建
打開
已保存
另存為
導(dǎo)出
打印
主題
偏好設(shè)置
關(guān)于
關(guān)閉
Future的使用
get(long timeout, TimeUnit unit)
package java.util.concurrent;
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;
}
這個(gè)接口是在異步線程中執(zhí)行計(jì)算,然后在主線程當(dāng)中能拿到異步線程計(jì)算的結(jié)果,如果異步線程中沒有執(zhí)行完炼列,主線程會(huì)阻塞住拴孤,等異步線程完了之后拿到結(jié)果。這個(gè)地方有兩個(gè)方法仅政,get()和get(long timeout, TimeUnit unit)祟昭,后面那個(gè)表示在時(shí)間范圍內(nèi)執(zhí)行未完成就拋出異常。
import java.util.concurrent.;
?
public class TestFuture {
static ExecutorService executorService = Executors.newSingleThreadExecutor();
?
public static void main(String[] args) {
try {
Future<Integer> future = caculate(3);
Thread.sleep(10000);
int output = future.get(2000, TimeUnit.MILLISECONDS);
System.out.println(output);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
public static Future<Integer> caculate (final Integer input){
return executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return inputinput;
}
});
?
}
}