Search code examples
javamultithreadingsynchronized

Java Multithreading synchronized usage


I am confused as to what will be the output of the following code(between the two options) and why: As per my understanding output should be option1 as synchronized keyword is used .

Output Options:

  1. Java Thread ThreadExample JavaMultithreading.
  2. The order in which text will be printed cannot be determined.
    class ThreadDemo extends Thread 
    { 
        final StringBuffer sb1 = new StringBuffer(); 
        final StringBuffer sb2 = new StringBuffer(); 

        public static void main(String args[]) 
        { 
            final ThreadDemo h = new ThreadDemo(); 

            new Thread() 
            { 
                public void run() 
                { 
                    synchronized(this) 
                    { 
                        h.sb1.append("Java"); 
                        h.sb2.append("Thread"); 
                        System.out.println(h.sb1); 
                        System.out.println(h.sb2); 
                    } 
                } 
            }.start(); 

            new Thread() 
            { 
                public void run() 
                { 
                    synchronized(this) 
                    { 
                        h.sb1.append("Mutithreading"); 
                        h.sb2.append("Example"); 
                        System.out.println(h.sb2); 
                        System.out.println(h.sb1); 
                    } 
                } 
            }.start(); }}





Solution

  • First, there is no telling which thread will run before the other. So you can't assert definitely that "Java thread" will precede "Mutithreading Example". It might happen, it might not.

    Second, the synchronized keyword on the run methods is irrelevant, because each thread is locking on its own monitor. So there's no reason to think that "Java" and "thread", for instance, have to be printed together without anything in between. It might happen, it might not.

    The locks that do matter here are on the StringBuffers, and on the stdout PrintStream. These objects use synchronized on their methods, acquiring the monitor and holding it for the duration of the method call. That prevents concurrent calls modifying the state of the same object from interfering with each other.