源码java.util.concurrent.Executor

Executor接口就一个方法void execute(Runnable command)

大致翻译下源码对类的注释

Executor对象用于执行提交的Runnable任务,这个接口提供了一种解藕提交上来的任务的运行方式(包括线程的使用,调度等)的方法。

Executor的使用主要用于替代直接明确的线程创建 比如:

相对于 new Thread(new (Runable Task())).start()这种为每个任务直接创建一个线程

Executor的处理方式是

Executor executor = new Executor();(实现)

executor.execute(new Runnable Task());

至于execute是如何处理每个任务则由各自的实现类去实现

Executor并没有严格要求说一定要异步的处理每个任务,举个简单的例子:

class DirectExecutor implements Executor {
    public void execute(Runnable r) {
      r.run();
    }
  }}

 这里executor就是立即执行提交的任务

当然普遍的是,任务会在其他线程执行,而不是调用线程:

class ThreadPerTaskExecutor implements Executor {
 *   public void execute(Runnable r) {
 *     new Thread(r).start();
 *   }
 * }}

Executor的许多实现会对任务的调用方式和调用时机做出限制,下面的例子中SerialExecutor将提交的任务队列的交给另一个executor,形成一个混合executor。(笔者注释:这里就做出限制先传进来的任务先处理)

class SerialExecutor implements Executor {
 *   final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
 *   final Executor executor;
 *   Runnable active;
 *
 *   SerialExecutor(Executor executor) {
 *     this.executor = executor;
 *   }
 *
 *   public synchronized void execute(final Runnable r) {
 *     tasks.offer(new Runnable() {
 *       public void run() {
 *         try {
 *           r.run();
 *         } finally {
 *           scheduleNext();
 *         }
 *       }
 *     });
 *     if (active == null) {
 *       scheduleNext();
 *     }
 *   }
 *
 *   protected synchronized void scheduleNext() {
 *     if ((active = tasks.poll()) != null) {
 *       executor.execute(active);
 *     }
 *   }
 * }}

Executor在本包的几个实现如:ExecutorService 是一个对功能扩展的接口,ThreadPoolExecutor提供了一个扩展的线程池实现,Executors则为这些Executor提供了方便的工厂方法

内存一致性影响:根据happen-before原则,在任务提交给Executor的动作之前的动作一定在任务运行开始之前完成,或许(即使)任务在另一个线程执行

猜你喜欢

转载自xiaoxiaoher.iteye.com/blog/2363677