0

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
Garrett
  • 1
  • 2

1 Answers1

6

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).

user2864740
  • 60,010
  • 15
  • 145
  • 220
yole
  • 92,896
  • 20
  • 260
  • 197
  • My explanation was simplified; actually synchronization depends on the specific stream implementation. In this case it happens inside PrintStream: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/PrintStream.java#770 – yole Dec 20 '14 at 17:28
  • 1
    Thanks folks, @yole -- however, now when I put a Thread.sleep(1) in the while loop, jvisualvm reports both the threads to be always sleeping. Also, jvisualvm does not show the main thread? – Garrett Dec 21 '14 at 17:56
  • @Garrett, I think this is a bug. See my question: https://stackoverflow.com/questions/44766524/thread-sleeps-for-too-long – LAFK 4Monica_banAI_modStrike Jun 26 '17 at 18:45