java線程池

相關類Executor,Executors,AbstractExecutorService,ExecutorService框架

Executor整個線程池執行者框架的頂層接口spa

public interface Executor {線程

    void execute(Runnable command);
}
orm

ExecutorService 定義了不少的方法:對象

public interface ExecutorService extends Executor {繼承

    void shutdown();接口

    List<Runnable> shutdownNow();it

    boolean isShutdown();io

    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;

}

AbstractExecutorService是一個抽象類,它實現了ExecutorService接口的submit,invokeAll的方法

public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }


    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

在這裏,全部submit方法提交的任務最終仍是調用了execute方法,execute是接口Executor中定義的方法,AbstractExecutorService沒有實現它,

須要子類去實現這個方法,ThreadPoolExecutor繼承了AbstractExecutorService,它實現了execute方法。ScheduledThreadPoolExecutor繼承自ThreadPoolExecutor,並覆蓋了ThreadPoolExecutor的execute方法。這個方法是線程執行框者架的核心邏輯,不一樣的線程池執行者有不一樣的實現邏輯。

ThreadPoolExecutor線程池執行者:它有一個核心的成員變量:

private final HashSet<Worker> workers = new HashSet<Worker>();

workers能夠看作是ThreadPoolExecutor中用於運行任務的線程池。

worker是一個封裝了一個Thread對象並實現了Runnable接口的類。封裝Thread很容易理解,由於它要利用Thread去運行execute方法提交過來的runnable任務

相關文章
相關標籤/搜索