走近Callable

HeJin小于 1 分钟JavaJUC并发编程

image-20210311192232745
image-20210311192232745
  • 可以有返回值。
  • 可以抛出异常。
  • 方法不同。call()方法。
@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
image-20210311192650508
image-20210311192650508

Runnable接口

image-20210311193457581
image-20210311193457581

FutureTask类是Runnable接口的实现类

FutureTask(Callable<V> callable)
Creates a FutureTask that will, upon running, execute the given Callable.
image-20210311193905916
image-20210311193905916
public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread myThread = new MyThread();
        // 适配类 FutureTask
        FutureTask futureTask = new FutureTask(myThread);
        new Thread(futureTask, "A").start();
        // 结果会被缓存,效率高
        new Thread(futureTask, "B").start();
        // 获取Callable的返回结果.get方法可能会产生阻塞
        Integer rst = (Integer) futureTask.get();
        // 或者使用异步同信来处理
        System.out.println(rst);
    }
}

class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("call()");
        // 耗时的操作
        return 1024;
    }
}

结果:

call()
1024

Process finished with exit code 0
  • 结果会被缓存,效率高。
  • get方法结果可能会等待,产生阻塞。