码迷,mamicode.com
首页 > 其他好文 > 详细

Executor 任务执行器

时间:2020-02-28 14:06:19      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:executor   ted   ext   tor   调度   cti   offer   span   active   

Executor:
  • 是一个接口
  • 用于执行提交的任务
  • 解耦任务提交和执行(线程的创建及调度)

Executor的实现可以根据实际需求延展不同的逻辑:
1. 对于提交的任务同步或者异步执行,如下同步执行:
class ThreadPerTaskExecutor implements Executor {
   public void execute(Runnable r) {
     new Thread(r).start();
}
2. 另起线程执行任务,如下:
 class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
     new Thread(r).start();
 }
3. 对于执行的任务添加限制:
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 任务执行器

标签:executor   ted   ext   tor   调度   cti   offer   span   active   

原文地址:https://www.cnblogs.com/niejunlei/p/12376728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!