Running notes with a synchronized method

I have some problems understanding the functionality of a synchronized keyword. According to java docs and other tutorials, it says that when a synchronized keyword is used, alternation between the operators of this method is NOT possible between two threads.

But please see the code snippet below.

public class LockThread implements Runnable { String name; public LockThread(String name) { this.name = name; } public static void main(String[] args) { new Thread(new LockThread("a")).start(); new Thread(new LockThread("b")).start(); } public void run() { locked(Thread.currentThread().getId()); } synchronized void locked(long l) { System.out.println(name+"-"+l + "---> Printed from " + Thread.currentThread().getName()); System.out.println(name+"-"+l + "---> Printed from " + Thread.currentThread().getName()); } } 

As I understand it, the output of programs should ALWAYS be such that Thread 0 and thread-1 should NOT alternate. But by executing this part of the code several times, I get alternating output.

  With interleaving (Output I expect)
     a-9 ---> Printed from Thread-0
     a-9 ---> Printed from Thread-0
     b-10 ---> Printed from Thread-1
     b-10 ---> Printed from Thread-1

 Without Interleaving (This is one another output I see for the same code above)
     a-9 ---> Printed from Thread-0
     b-10 ---> Printed from Thread-1
     a-9 ---> Printed from Thread-0
     b-10 ---> Printed from Thread-1

Please help me deal with the problem.

Thanks in advance.

+4
source share
1 answer

The synchronized prevents the start of two threads from code synchronized on the same object.

Each of your threads is synchronized with another object ( this ), so it has no effect.

+5
source

All Articles