深入理解Executor

一、Executor的定义和用途

1.decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.

将任务提交和每个任务怎么运行(包括线程使用的细节、线程的调度)解耦

2.An Executor is normally used instead of explicitly creating threads

使用场景:使用时一般不显式创建线程

例如:

显式线程:

new Thread(new(RunnableTask())).start();

Executor使用:

 Executor executor = anExecutor;   //需要创建一个Class implements Executor
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());

一、Executor的使用

1.Executor可以不异步执行,此时,Executor是在调用者的线程中执行此方法

class DirectExecutor implements Executor {
     public void execute(Runnable r) {
         r.run();
     }
 }
2.Executor也可以在新开辟的线程中执行此方法
 class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
         new Thread(r).start();
     }
 }
3.序列化任务(没看懂)
Many Executor implementations impose some sort of limitation on how and when tasks are scheduled.  The executor below serializes the submission of tasks to a second 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);
     }
   }
 }














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值