Executor入门 | Executor框架
程序员文章站
2022-04-04 09:11:55
...
讲到并发就不得不讲一下Executor框架,其框架主要类关系图如下:
从图中可以看出来,接口Executor是框架知识点的引路者,那就从它讲起!
一:关于Executor的源码
/* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; /** * An object that executes submitted {@link Runnable} tasks. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, etc. An <tt>Executor</tt> is normally used * instead of explicitly creating threads. For example, rather than * invoking <tt>new Thread(new(RunnableTask())).start()</tt> for each * of a set of tasks, you might use: * * @since 1.5 * @author Doug Lea */ public interface Executor { /** * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the <tt>Executor</tt> implementation. * * @param command the runnable task * @throws RejectedExecutionException if this task cannot be * accepted for execution. * @throws NullPointerException if command is null */ void execute(Runnable command); }
说明:看源码,简单的不得了,就一个execute方法,参数为Runnable类型的对象!学过线程的都应该知道,Thread类就是Runnable的实现类,那execute方法可以传Thread对象。
在这列举一下Runnable的实现类:
- AsyncBoxView.ChildState 用于Java Swing开发
- FutureTask 用于异步计算
- RenderableImageProducer 用于AWT开发图像异步生成
- SwingWorker 用于Java Swing开发
- Thread 用于Java线程开发
- TimerTask 用于计时器任务
其中标红的是需要重点学习的!
二:Executor的几种实现形式
在Executor的源码中,列举了几种实现方式:
1) 执行程序可以在调用者的线程中立即运行已提交的任务
class DirectExecutor implements Executor { public void execute(Runnable r) { r.run(); } }
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); } } }
参考资料:
JDK API 1.6.0
http://www.iteye.com/topic/366591