Reputation: 1
I am running the following program in Java (through Eclipse IDE):
package threaddemo;
class Runner extends Thread{
@Override
public void run() {
while(true)
System.out.println("Running in a thread ....");
}
}
public class ThreadClass {
public static void main(String[] args) {
Runner thread1 = new Runner();
thread1.start();
Runner thread2 = new Runner();
thread2.start();
}
}
While the program runs, I am trying to see the thread activity in JVisualVM. I was expecting to see both the threads in green concurrently (i.e. running concurrently), however I see that at any point in time during execution, for a little while any one thread is in the Monitor state, while the other is being executed. After a little while, they switch (the former is executing, while the latter is in Monitor state). How can this be?
Upvotes: 0
Views: 96
Reputation: 97338
Both of your threads are trying to write to System.out. Since writing to PrintStream is synchronized, at every time one of your threads is writing to the stream and another is waiting for the stream to become available.
You would be able to see threads executing at the same time if they performed some activity that does not depend on a shared resource (for example, some computation).
Upvotes: 6