我对同步块的假设是否正确?
我有一个带有同步块的方法shout()。
private void shout(){
System.out.println("SHOUT " + Thread.currentThread().getName());
synchronized(this){
System.out.println("Synchronized Shout" + Thread.currentThread().getName());
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Synchronized Shout" + Thread.currentThread().getName());
}
}
如果我有两个运行此方法的线程,我是否正确地假设两个“同步喊叫”总是一个接一个地出现? “同步呐喊”之间不能有其他语句吗?
I have a method shout() with a synchronized block.
private void shout(){
System.out.println("SHOUT " + Thread.currentThread().getName());
synchronized(this){
System.out.println("Synchronized Shout" + Thread.currentThread().getName());
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Synchronized Shout" + Thread.currentThread().getName());
}
}
If I have two Threads that run this method, am I correct in assuming that the two "Synchronized Shout" will always appear one after the other? There can be no other statements in between the "Synchronized Shout"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只要
this
引用相同即可。如果在两个不同的对象上运行代码,锁将不起作用。请注意,如果您要在
this
上使用Object.wait
而不是调用Thread.sleep
来延迟,那么锁将被删除(并且在继续之前重新获得)。So long as the
this
reference is the same. If you run the code on two different objects, the lock will have no effect.Note, if you were to use
Object.wait
onthis
instead of callingThread.sleep
to delay, then the lock would be removed (and reacquired before moving on).由于打印“SHOUT...”的行不需要锁定,因此它可以出现在任何点。因此,即使一个线程持有锁,另一个线程也可能会进来并打印“SHOUT...”。
以下代码显示了交错:
它打印出来
Since the line that prints "SHOUT..." does not require a lock, it can appear at any point. Thus, even if one thread is holding the lock, another thread may come in and print "SHOUT...".
The following code shows the interleaving:
It prints out
当两个或多个线程针对同一个实例运行时,SHOUT 可以出现在任何地方,因为它位于同步块之外,因此不受保护。 “同步喊叫”将始终严格按顺序出现,不会有来自另一个线程的同步喊叫介入并影响顺序。
When two or more threads are running against the same instance, then the SHOUT can appear anywhere, because it's outside the synchronized block, and thus unguarded. The "synchronized shout"s will always appear strictly in order, with no synchornized shout from another thread getting in between and affecting the order.