Callable、Future和FutureTask
Callable
- Runnable没有返回值:public abstract void run();,Callable可以有返回值:V call() throws Exception;
- 可以抛出异常
- 方法不同,run()/call()
- 源码
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;
}
Future
- Future只是一个接口
- 能判断任务是否完成;能够中断任务;能够获取任务执行结果。
- 源码
public interface Future<V> {
// 如果取消已经完成的任务会返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
boolean cancel(boolean mayInterruptIfRunning);
// 是否被取消成功
boolean isCancelled();
// 是否已经完成
boolean isDone();
// 获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回
V get() throws InterruptedException, ExecutionException;
// 如果在指定时间内,还没获取到结果,就直接返回null
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask
-
FutureTask是Future接口的一个唯一实现类
-
继承关系
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
public class FutureTask<V> implements RunnableFuture<V>
RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
- 构造方法
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW;
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW;
}
- Callable+Future
import java.util.concurrent.*;
class MyCallable {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
Future<Integer> result = executor.submit(task);
executor.shutdown();
TimeUnit.SECONDS.sleep(1);
System.out.println("主线程在执行任务");
try {
System.out.println("task运行结果" + result.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
}
class Task implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("子线程在进行计算");
TimeUnit.SECONDS.sleep(2);
int sum = 0;
for (int i = 0; i < 100; i++)
sum += i;
return sum;
}
}
- Callable+FutureTask
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyCallable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// new Thread(new Runnable()).start();
// new Thread(new FutureTask<V>()).start();
// new Thread(new FutureTask<V>( Callable )).start();
MyThread myThread = new MyThread();
FutureTask<Integer> integerFutureTask = new FutureTask<>(myThread); // 适配类
new Thread(integerFutureTask, "A").start();
new Thread(integerFutureTask, "B").start(); // 结果会被缓存,只会打印一个call
Integer o = integerFutureTask.get(); // 返回值 此方法可能会产生阻塞,最好放在最后一行
System.out.println(o);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("call()");
return 7;
}
}