美文网首页
Callable与Future的使用

Callable与Future的使用

作者: 小媛不见了 | 来源:发表于2018-08-24 14:50 被阅读0次

Callable与Runnable的区别:

1.Callable可以返回结果

2.Callable可以抛出异常

Callable一般配合Future与FutureTask使用:

    public static void main(String[] args) {

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

        // threadA
        Future<String> futureA = fixedThreadPool.submit(() -> "A " + Thread.currentThread().getName());

        // threadB
        Future<String> futureB = fixedThreadPool.submit(() -> {
            Thread.sleep(1000);
            return "B " + Thread.currentThread().getName();
        });

        // threadC
        Future<String> futureC = fixedThreadPool.submit(() -> {
            Thread.sleep(5000);
            return "C " + Thread.currentThread().getName();
        });

        try {
            System.out.println(futureA.get());
            System.out.println(futureB.get());
            System.out.println(futureC.get(1000, TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

执行结果:

A pool-1-thread-1
B pool-1-thread-2
java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at com.pajk.apate.biz.UserBiz.main(UserBiz.java:145)

Future.java

/**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     */
// 等待直到返回结果
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     */
// 最多等待设置的时间,超时抛出TimeoutException
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

相关文章

网友评论

      本文标题:Callable与Future的使用

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