Runnable、Callable、Future和FutureTask

Runnable、Callable、Future和FutureTask

线程池:
继承关系:ThreadPoolExecutor->ExecutorService->Executor
Executors:ThreadPoolExecutor的工厂类,生成不同的线程池

主要关系:在线程池中:

<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任务的执行结果进行取消、查询是否完成、获取结果。
必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

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的实现类,用来实现真正的Future工作,用来对Callable或者Runbale的任务实现监控:
构造方法:
注意第二个,因为Runnable无返回值,所以要手动提前写一个结果,当Runnable执行完毕返回这个值,当然不关心返回值的话传null

public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}

线程池继承关系:
继承关系: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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容