Java多线程——Callable和future

Callable和future

  • Callable
  • Future
  • RunnableFuture
  • FutureTask

Callable

Runnable封装了一个异步运行的任务,其run()方法是一个没有参数和值的异步方法

而Callable中的call()方法是带有返回值为模板参数T的异步方法,其源码为

public interface Callable {
	V call() throws Exception;
}

Future

Future保存异步计算的结果,可以启动一个计算交给线程,在计算完结果后就可以得到它,其源码为

public interface Future {
	boolean cancel(boolean mayInterruptIfRunning);
	boolean isCancelled();
	boolean isDone();
	V get() throws InterruptedException, ExecutionException;
	V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
  • 若在计算未完成前调用get()将被阻塞
  • 若在计算未完成前,调用get(long timeout, TimeUnit unit)且超时将抛出异常
  • cancel(boolean mayInterruptIfRunning)可以取消计算,若还没开始则不再开始

RunnableFuture

RunnableFuture又是Future和Runable的子类,其源码为

public interface RunnableFuture extends Runnable, Future {
    void run();
}

FutureTask

FutureTask包装器可将Callable转为Future和Runable,它是RunnableFuture的子类,如下开启一个计算线程,转为Runnable传入到Thread,再转为Future获取计算的结果

Callable myComputation = new Callable() {
    @Override
    public Integer call() throws Exception {
        return 1;
    }
};
FutureTask task = new FutureTask<>(myComputation);
Thread thread = new Thread(task);
thread.start();
try {
    Integer result = task.get();
} catch (Exception e) {
    e.printStackTrace();
}

你可能感兴趣的:(#,java多线程,java,前端,服务器)