我在理解同步关键字功能时遇到一些困难。
根据java文档和其他教程,据说当使用synchronized关键字时,两个线程之间不可能在该方法的语句之间进行交错。
但是,请看下面的代码。
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());
}
}
根据我的理解,程序输出应该始终以线程 0 和线程 1 不应该交错的方式进行。
但是多次执行这段代码,我得到了交错的输出。
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
请帮我理解这个问题..
提前致谢..
The synchronized
关键字可防止两个线程运行在同一对象上同步的代码。
每个线程都在不同的对象上同步(this
),所以没有效果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)