线程池Executor执行线程(一)

 Executor接口:

public interface Executor {

    /**
         在将来的某个时间执行给定的命令。 该命令可以在新线程、池线程或调用线程中执行,具体取决于 {@code Executor} 实现。
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

主要实现接口:

public interface ExecutorService extends Executor
public class ThreadPoolExecutor extends AbstractExecutorService 
public class ScheduledThreadPoolExecutor
        extends ThreadPoolExecutor
        implements ScheduledExecutorService
public interface ScheduledExecutorService extends ExecutorService 

了解下ExecutorService的几个常用方法:

   //启动有序关闭,其中先前提交任务被执行,但不会接受任何新任务。如果已经关闭,调用没有额外的效果。
    void shutdown();


   //会返回线程执行完成的一个结果
   <T> Future<T> submit(Callable<T> task);


   //提交一个 Runnable 任务执行并返回一个 Future任务。将在线程执行完成后返回null。
   Future<?> submit(Runnable task);


   //提交一个 Runnable 任务执行并返回一个 Future 代表那个任务。将在线程成功完成后返 回给定的结果。
   <T> Future<T> submit(Runnable task, T result);

    在AbstractExecutorService类中有部分API接口实现
    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;
    }
    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;
    }

看上面的源码,发现他们在执行的时候都有用到 FutureTask这个类,接下来进入这个类,去查看具体用法:

public class FutureTask<V> implements RunnableFuture<V> {
      此任务的运行状态,最初为 NEW。 运行状态仅在方法集中转换到终止状态,
      设置异常,并取消。 在完成期间,状态可能会出现COMPLETING 的瞬态值(设置结果时)
      或INTERRUPTING(仅在打断跑步者以满足取消(真))。 从这些中间到最终的过渡状态使用更便宜的有序/延迟写入,因为值是唯一的
      并且不能进一步修改。
      可能的状态转换:
     NEW -> COMPLETING -> NORMAL
     NEW -> COMPLETING -> EXCEPTIONAL
     NEW -> CANCELLED
     NEW -> INTERRUPTING -> INTERRUPTED
    private volatile int state;
    private static final int NEW          = 0;
    private static final int COMPLETING   = 1;
    private static final int NORMAL       = 2;
    private static final int EXCEPTIONAL  = 3;
    private static final int CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;

    //创建一个 {@code FutureTask},它将在运行时执行给定 {@code Callable}。
     public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    //创建一个 {@code FutureTask},它将在运行时执行给定 {@code Runnable},并安排 {@code get} 将返回成功完成后给出结果。
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

    protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

   public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }


}
 

下面在看下这几个接口方法:

public interface Future<V> {
    //尝试取消此任务的执行。 如果任务已经完成,已经被取消,则失败,或因其他原因无法取消。 
    如果成功,并且在调用方法时此任务尚未启动,这个任务永远不应该运行。 
    如果任务已经开始,然后 {@code mayInterruptIfRunning} 参数确定 执行这个任务的线程是否应该被中断,试图停止任务。
    boolean cancel(boolean mayInterruptIfRunning);
    //如果此任务在完成之前被取消,则返回true
    boolean isCancelled();
    //如果此任务完成,则返回 {@code true}。
    boolean isDone();
    //如有必要,等待计算完成,然后检索其结果。
    V get() throws InterruptedException, ExecutionException;
    //如有必要,最多等待给定的计算时间完成,然后检索其结果(如果可用)。
    V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;
}

@FunctionalInterface
public interface Runnable {
    /**
     * 当使用实现接口 <code>Runnable</code> 的对象时创建线程,启动线程导致对象的 <code>run</code> 方法在单独执行时被调用
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员路同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值