深入理解Executor

来源:互联网 发布:linux ls 隐藏文件 编辑:程序博客网 时间:2024/05/21 09:08

一、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);     }   } }














0 0
原创粉丝点击