Reputation: 1086
I came across below code snippet while reading ExecutorService
section from book Java 8 The complete reference
.
Below code snippet explains how ExecutorService
works.
// 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();
}
}
}
What I am not able to understand is the last line in the constructor of class MyThread
.
The constructor of MyThread
creates an Object of Thread
using
new Thread(this)
However, this newly created thread is never started by calling start()
method. Also, according to my understanding ExecutorService
creates and manages its own threads to run our runnable
task. Then why is this Thread
object being created in this case?
Upvotes: 2
Views: 2093
Reputation: 48258
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;
Upvotes: 2