I am seeing interesting behavior. I am running this code
public class ThreadsTest {
public static void main(String[] args) {
Runnable mr = new MyRunnable();
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
t1.setName("first");
t2.setName("second");
t1.start();
t2.start();
t1.run();
}
}
class MyRunnable implements Runnable {
public void run() {
for (int i=0; i < 2; i++) {
System.out.println("Running: " + Thread.currentThread().getName());
}
}
}
The output I get is:
Running: first
Running: first
Running: second
Running: second
I am expecting to see something similar to this:
Running: first
Running: first
Running: second
Running: second
Running: main
Running: main
Does anyone knows why I don’t see Running: main somewhere in my output. Thank you.
The explanation is a bit subtle.
The default behaviour of the
Thread.run()method is described as running the suppliedRunnableif it exists, and doing nothing otherwise.The subtlety is that when a Thread exits, the
exit()method “aggressively” nulls out reference fields to prevent storage leaks. (Here’s the source … line 720 onwards.) It appears that by the time that you calledt1.run()inmain, the thread had exited so the call was a no-op.Naturally, the output depends on whether or not the
mainthread gets to run again before the child thread exits … and that will depend on your platform; e.g. what the JVM and the OS-level thread scheduler do and how many cores are available.