首页 > java Executor类的注释部分什么意思?

java Executor类的注释部分什么意思?

许多 Executor 实现都对调度任务的方式和时间强加了某种限制。以下执行程序使任务提交与第二个执行程序保持连续,这说明了一个复合执行程序。
 class SerialExecutor implements Executor {
     final Queue<Runnable> tasks = new LinkedBlockingQueue<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是干什么的, 怎么连续的提交任务?


关于 Executor 可以参考 java并发编程-Executor框架。SerialExecutor 的作用是使用指定的(通过构建函数传入)Executor 对象,顺序的执行任务(通过 execute() 方法实现)

SerialExectuor.execute() 会把传入的 Runnable 放在队列里,然后按顺序执行,如果队列为空(初始或已经执行完),会立即启动传入的 Runnable 对象,用法大概就像这样

SerialExecutor sExecutor = new SerialExecutor(sourceExecutor);
sExecutor.execute(task1);
sExecutor.execute(task2);
sExecutor.execute(task3);
// ...

SerialExecutor与其他Executor的区别在于,使用execute(final Runnable r)提交任务时,如果当前任务执行完成之后,会继续执行下一个任务,也就是代码种finally里面的scheduleNext();这句起的作用,所以就是连续执行了。

普通的Executor框架是通过调度器自身的线程的run方法中无线循环读取队列中的任务去触发任务的执行,而SerialExecutor在每个任务中显示的调用了scheduleNext来触发下一个任务的执行。

【热门文章】
【热门文章】