Callable与Future的使用

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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容