Callable与Future的使用

Callable与Runnable的区别:

1.Callable可以返回结果

2.Callable可以抛出异常

Callable一般配合Future与FutureTask使用:

    public static void main(String[] args) {

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

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

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

        // threadC
        Future 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的使用)