Java ExecutorService - 创建一个新线程但不启动它

Java ExecutorService - Creating a new thread but not starting it

我在阅读 Java 8 The complete reference 一书的 ExecutorService 部分时看到了下面的代码片段。

下面的代码片段解释了 ExecutorService 的工作原理。

// A simple example that uses an Executor.

import java.util.concurrent.*;

class SimpExec {

    public static void main(String args[]) {
        CountDownLatch cdl = new CountDownLatch(5);
        CountDownLatch cdl2 = new CountDownLatch(5);
        CountDownLatch cdl3 = new CountDownLatch(5);
        CountDownLatch cdl4 = new CountDownLatch(5);
        ExecutorService es = Executors.newFixedThreadPool(2);
        System.out.println("Starting");
        // Start the threads.
        es.execute(new MyThread(cdl, "A"));
        es.execute(new MyThread(cdl2, "B"));
        es.execute(new MyThread(cdl3, "C"));
        es.execute(new MyThread(cdl4, "D"));
        try {
            cdl.await();
            cdl2.await();
            cdl3.await();
            cdl4.await();
        } catch (InterruptedException exc) {
            System.out.println(exc);
        }
        es.shutdown();
        System.out.println("Done");
    }
}

class MyThread implements Runnable {

    String name;
    CountDownLatch latch;

    MyThread(CountDownLatch c, String n) {
        latch = c;
        name = n;
        new Thread(this);
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + ": " + i);
            latch.countDown();
        }
    }
}

我无法理解的是 class MyThread 的构造函数中的最后一行。

MyThread 的构造函数使用

创建了 Thread 的对象

new Thread(this)

但是,这个新创建的线程永远不会通过调用 start() 方法来启动。此外,根据我的理解,ExecutorService 创建并管理自己的线程以 运行 我们的 runnable 任务。那么为什么在这种情况下要创建这个 Thread 对象?

这一行:

new Thread(this);

对代码的执行没有影响,您可以毫无问题地删除...

执行器会创建自己的线程来执行代码

你可以通过以下方式验证这行代码没有生效:

  1. 从代码中删除该行(它会得到相同的结果)
  2. 为线程命名并调试new Thread(this, "T: " + n);你会看到堆栈中没有出现具有这样名称的线程
  3. 您可以查看 ThreadPoolExecutor 的源代码并验证方法 private boolean addWorker(Runnable firstTask, boolean core) 是否正在从您作为参数提供的可运行对象创建一个新的工作程序,并且他们这样做

--

w = new Worker(firstTask);
final Thread t = w.thread;