问题
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