Statement execution interleaving with Synchronized method execution

。_饼干妹妹 提交于 2019-12-30 10:17:09

问题


I have some trouble in understanding the synchronized keyword functionality. As per java documentations and other tutorials, it is being said that when synchronized keyword is used, interleaving between the statements of that method is NOT possible between the two threads.

But, please see the below piece of code.

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 per my understanding, the programs output should ALWAYS be in a way that Thread 0 and thread-1 should NOT interleave.. But executing this piece of code multiple times, I get an interleaved 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 understand the issue..

Thanks in advance..


回答1:


The synchronized keyword prevents two threads from running code that is synchronized on the same object.

Each of your threads are synchronizing on a different object (this), so it has no effect.



来源:https://stackoverflow.com/questions/18939908/statement-execution-interleaving-with-synchronized-method-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!