java方法同步对象
我只是想确保我正确理解以下内容。
- 方法上的synchronized关键字禁止在类的一个实例上同时运行两个这样的方法。
- 同步对象是有问题的实例。
如果这是真的,下面的例子应该是正确的,
class Example
{
public synchronized void method1()
{
// mark 1 - never here when other thread at mark 2 or 4
}
public synchronized void method2()
{
// mark 2 - never here when other thread at mark 1 or 4
}
public void method3()
{
// mark 3 - may be (!) here when other thread at mark 1, 2 or 4
synchronized (this)
{
// mark 4 - never here when other thread at mark 1 or 2
}
}
}
感谢“是”或伪造。 乙
I just wanted to be sure that I understood the following right.
- The synchronized keyword on methods forbids two such methods to be run simultaneously on one instance of the class.
- The synchronization object is the instance in question.
If this is true the following example should be right
class Example
{
public synchronized void method1()
{
// mark 1 - never here when other thread at mark 2 or 4
}
public synchronized void method2()
{
// mark 2 - never here when other thread at mark 1 or 4
}
public void method3()
{
// mark 3 - may be (!) here when other thread at mark 1, 2 or 4
synchronized (this)
{
// mark 4 - never here when other thread at mark 1 or 2
}
}
}
Thx for a 'yes' or falsification.
b
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的理解是正确的。
请参阅以下内容以进行进一步讨论:在 Java 中避免同步(this)?
Your understanding is correct.
Take a look at the following for further discussion: Avoid synchronized(this) in Java?
你说的是正确的。
添加一件事,如果该方法是静态方法,则 Class 就是锁。
What you've said is correct.
And to add one thing, if the method is a static method, the Class is the lock.