Executor接口 谁借莪1个温暖的怀抱¢ 2022-08-03 00:25 96阅读 0赞 最近在学习Executor的源码,整理翻译如下: 说明: 只是为了加深印象并鼓励自己~~ package java.util.concurrent; /** * 一个执行提交的Runnable任务的类.这个接口从每个任务如何执行的角度上提供了一种解耦的任务提交的方式,其 * 中包含了线程的使用、调度等细节.一个Executor的使用替代了以往的显示地创建线程.举个例子来说,以往需要触 * 发new Thread(new(RunnableTask())).start() 来执行一系列的任务,现在你或许可以这样使用: * <pre> * Executor executor = <em>anExecutor</em>; * executor.execute(new RunnableTask1()); * executor.execute(new RunnableTask2()); * ... * </pre> * * 然而,Executor 接口并不是严格要求执行是异步的。在最简单的情况下,执行者可以立即在调用方的线程中运行提 * 交的任务: * * <pre> { @code * class DirectExecutor implements Executor { * public void execute(Runnable r) { * r.run(); * } * }}</pre> * * 更典型的是,任务在一些线程中被执行,而不是调用方的线程。在每个任务的执行中产生新线程。 * * <pre> {@code * class ThreadPerTaskExecutor implements Executor { * public void execute(Runnable r) { * new Thread(r).start(); * } * }}</pre> * * 许多Executor 实现对任务的调度和何时执行的限制强加了一些限制。下面的执行序列化任务提交到另一个执行者, * 说明复合执行。 * * <pre> {@code * 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); * } * } * }}</pre> * * Executor 在这个包里有一个更广泛的实现接口 ExecutorService. * ThreadPoolExecutor类提供了一个可扩展的线程池的实现. * Executors 类为这些执行提供了更加方便的工厂方法. * * 内存一致性效果:线程中将 Runnable 对象提交到 Executor 之前的操作 happen-before 其执行开始(可 * 能在另一个线程中)。 * * @since 1.5 * @author Doug Lea */ public interface Executor { /** * Executors在将来的某个时间被命令执行。这个命令可能在一个新线程中被执行,在合并线程,或者调用线 * 程. 这个由Executor的实现者自由裁定。 * * @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); }
还没有评论,来说两句吧...