多线程如何理解Java API文档中的接口执行器示例
有人能详细解释一下这段代码吗
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);
}
}
}
我正在学习java并发编程。当我查看这段代码时,我感到不知所措。主要有两点让我困惑:
- 为什么要在Executor中定义
Executor executor
,这是如何工作的李> - 它在
public synchronized void execute(final Runnable r)
中创建new Runnable(){}
并在这些Runnable中调用Runnable r.run()?这是什么李>
# 1 楼答案
SerialExecutor
是一个使用decorator模式的包装器实现。您可以使用Executor
接口的任何实现来实例化它,也可以在需要Executor
的地方将其作为参数传递例:
有关更多信息,请参阅^{} 类Java API文档
在上述方法中,在新的
Runnable
实例中调用r.run()
,因为在finally block中调用r.run()
的末尾,需要调用scheduleNext()
方法