有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程如何理解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并发编程。当我查看这段代码时,我感到不知所措。主要有两点让我困惑:

  1. 为什么要在Executor中定义Executor executor,这是如何工作的
  2. 它在public synchronized void execute(final Runnable r)中创建new Runnable(){}并在这些Runnable中调用Runnable r.run()?这是什么

共 (1) 个答案

  1. # 1 楼答案

    1. why define Executor executor inside Executor, how this works?

    SerialExecutor是一个使用decorator模式的包装器实现。您可以使用Executor接口的任何实现来实例化它,也可以在需要Executor的地方将其作为参数传递

    例:

    SerialExecutor se = new SerialExecutor(Executors.newFixedThreadPool(10));
    Executor anotherExecutor = se;
    

    有关更多信息,请参阅^{}类Java API文档

    1. In public synchronized void execute(final Runnable r) it create new Runnable(){} and in these Runnable, it call Runnable r.run()? what is this?

    在上述方法中,在新的Runnable实例中调用r.run(),因为在finally block中调用r.run()的末尾,需要调用scheduleNext()方法