许多 Executor 实现都对调度任务的方式和时间强加了某种限制。以下执行程序使任务提交与第二个执行程序保持连续,这说明了一个复合执行程序。
class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new LinkedBlockingQueue<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是干什么的, 怎么连续的提交任务?
For information about Executor, please refer to Java Concurrent Programming-Executor Framework. The function of
SerialExecutor
is to use the specified (passed in through the constructor function)Executor
object to execute tasks sequentially (implemented through theexecute()
method)SerialExecutor
的作用是使用指定的(通过构建函数传入)Executor
对象,顺序的执行任务(通过execute()
方法实现)SerialExectuor.execute()
会把传入的Runnable
放在队列里,然后按顺序执行,如果队列为空(初始或已经执行完),会立即启动传入的Runnable
SerialExectuor.execute()
will put the incomingRunnable
in the queue, and then execute it in sequence. If the queue is empty (initial or has been executed), it will be executed immediately Start the passed inRunnable
object, the usage is probably like this🎜The difference between SerialExecutor and other Executors is that when you use execute(final Runnable r) to submit a task, if the current task is completed, it will continue to execute the next task, which is the role of scheduleNext(); in the code finally. , so it is executed continuously.
The ordinary Executor framework reads the tasks in the queue in a wireless loop through the run method of the scheduler's own thread to trigger the execution of the task, while the SerialExecutor explicitly calls scheduleNext in each task to trigger the execution of the next task.