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

时间:2017-06-12 16:35:59

标签: java multithreading executorservice

我在阅读书籍ExecutorService中的Java 8 The complete reference部分时遇到了以下代码段。

以下代码段解释了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();
        }
    }
}

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

MyThread的构造函数使用

创建一个Thread的对象
  

new Thread(this)

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

1 个答案:

答案 0 :(得分:2)

this line:

new Thread(this);

is taking no effect on the execution of the code and you can removed without a problem...

the executor will create its own thread in order to execute the code

you can verify that this line of code is not taking effects by:

  1. removing the line from the code (it will get the same result)
  2. giving a name to the thread and debuggin new Thread(this, "T: " + n); you will see that no thread with such a name appears in the stack
  3. you can cehck the source code of the ThreadPoolExecutor and verify that the method private boolean addWorker(Runnable firstTask, boolean core) is creating a new worker from the runnable you gave as parameter and from that they do

--

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