Runnable、Callable、Future和FutureTask
線程池:
繼承關(guān)系:ThreadPoolExecutor->ExecutorService->Executor
Executors:ThreadPoolExecutor的工廠類,生成不同的線程池
主要關(guān)系:在線程池中:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
Callable:
位于java.util.concurrent包下,類似于Runnable:
public interface Callable<V> {
V call() throws Exception;
}
Future類:
位于java.util.concurrent包下
Future就是對于具體的Runnable或者Callable任務(wù)的執(zhí)行結(jié)果進行取消、查詢是否完成、獲取結(jié)果。
必要時可以通過get方法獲取執(zhí)行結(jié)果,該方法會阻塞直到任務(wù)返回結(jié)果。
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask:
FutureTask是Future的實現(xiàn)類,用來實現(xiàn)真正的Future工作,用來對Callable或者Runbale的任務(wù)實現(xiàn)監(jiān)控:
構(gòu)造方法:
注意第二個,因為Runnable無返回值,所以要手動提前寫一個結(jié)果,當(dāng)Runnable執(zhí)行完畢返回這個值,當(dāng)然不關(guān)心返回值的話傳null
public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}
線程池繼承關(guān)系:
繼承關(guān)系:ThreadPoolExecutor->ExecutorService->Executor
Executors:ThreadPoolExecutor的工廠類,生成不同的線程池
public interface Executor {
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}