区别,看代码
public class Thread implements Runnable
public interface Runnable {
public abstract void run();
}
public interface Callable<V> { V call() throws Exception; }
我要说的是,当你在线程池submit一个任务的时候发生了什么:
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
runnable被包装成了一个callable赋值给futuretask的callable域。其实你提交之后返回的是一个持你原来任务的future的对象,execute(ftask)就是分配线程执行任务,即调用call方法,call调用run,但是run是没有返回值的。然后当你用future.get()时候(可以设置超时),他会检查你的状态,执行完或者异常了就会返回。futuretask的run方法会调用set/setException去把结果放在outcome对象中,这俩方法都会调用finishCompletion(),它又会调用done方法,所以你可以重写done方法来做一些当任务完成时(包括异常完成)需要的操作。