Swathi
Swathi

Reputation: 580

Output of Anonymous Thread class is not synchronized

I have the following code snippet.

public class Test {
     static final StringBuffer sb1 = new StringBuffer();  
     static final StringBuffer sb2 = new StringBuffer();  
     public static void main(String args[])  
     {  
        new Thread()  
        {  
           public void run()  {  
            synchronized(this)  
            {  
                try {
                sb1.append("A");  
                sb2.append("B"); 
                System.out.println (sb1 + " " + sb2);   
                Thread.currentThread().sleep(5000);  
                    h.sb1.append("U"); 
                    h.sb2.append("V");
                    System.out.println (sb1 + " " + sb2);  
                 } catch (InterruptedException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }
            }  
           }  
        }.start();   
        new Thread() 
        { 
        public void run() 
        { 
            synchronized(this) 
            { 
                sb1.append("C"); 
                sb2.append("D"); 
                System.out.println (sb1 + " " + sb2);  
            } 
        }  
    }.start(); /* Line 28 */

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

    }
}

And when I run the program looks like it is not synchronized at object level. The output I'm getting is:

A B
AC BD
ACE BDF
ACEU BDFV

And I'm expecting the expected output as

A B
AU BV
AUC BVD
AUCE BVDF

Can someone please clarify what does this keyword refer to? Also if I use synchronize(this.getThreadGroup()) instead of synchronized(this). I get the output the expected output.

Upvotes: 0

Views: 343

Answers (1)

JohnnyAW
JohnnyAW

Reputation: 2876

synchronized(this)

can't work in this case, since this would refer to the Thread object and every run function is running in the own Thread.

if you use synchronized(sb1) your code should work as intended. You can synchronize on every object you want, java will lock the object on the statement and release it after the brackets. You should simply care, that you really synchronize on the same object.

Upvotes: 3

Related Questions