Future的使用

菜单
新建
打开
已保存
另存为
导出
打印
主题
偏好设置
关于
关闭
Future的使用

get(long timeout, TimeUnit unit)
package java.util.concurrent;
public interface Future {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
这个接口是在异步线程中执行计算,然后在主线程当中能拿到异步线程计算的结果,如果异步线程中没有执行完,主线程会阻塞住,等异步线程完了之后拿到结果。这个地方有两个方法,get()和get(long timeout, TimeUnit unit),后面那个表示在时间范围内执行未完成就抛出异常。

import java.util.concurrent.;

public class TestFuture {
static ExecutorService executorService = Executors.newSingleThreadExecutor();

public static void main(String[] args) {
try {
Future 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 caculate (final Integer input){
return executorService.submit(new Callable() {
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return input
input;
}
});

}
}

你可能感兴趣的:(Future的使用)