Callable

public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //new Thread(new Runnable()).start();
        //new Thread(new FutureTask<>()).start();
        //new Thread(new FutureTask<>(Callable)).start();
        MyThread myThread = new MyThread();
        //适配器 FutureTask
        FutureTask futureTask = new FutureTask(myThread);
        new Thread(futureTask,"A").start();
        //获取Callable的返回结果
        Integer out = (Integer) futureTask.get();
        System.out.println(out);
    }
}

class MyThread implements Callable{

    @Override
    public Integer call() throws Exception {
        System.out.println("Call()");
        return 1024;
    }
}

需要留意:

  • 多线程并发的情况下,使用Callable,运行结果会做缓存处理,提高效率。
  • 获取返回标识可能会遇到阻塞,一般会放在程序最后执行,或者采取异步调用方式。

你可能感兴趣的:(Callable)