我在阅读书籍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
对象?
答案 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:
new Thread(this, "T: " + n);
you will see that no thread with such a name appears in the stackprivate 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;