美文网首页
Future的使用

Future的使用

作者: 大数据修行 | 来源:发表于2020-03-23 21:13 被阅读0次

    菜单
    新建
    打开
    已保存
    另存为
    导出
    打印
    主题
    偏好设置
    关于
    关闭
    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;
    }
    这个接口是在异步线程中执行计算,然后在主线程当中能拿到异步线程计算的结果,如果异步线程中没有执行完,主线程会阻塞住,等异步线程完了之后拿到结果。这个地方有两个方法,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<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 input
    input;
    }
    });

    }
    }

    相关文章

      网友评论

          本文标题:Future的使用

          本文链接:https://www.haomeiwen.com/subject/shugyhtx.html