Java同步方法问题
我的类有两个同步方法:
class Service {
public synchronized void calc1();
public synchronized void calc2();
}
两者都需要相当长的时间来执行。问题是这些方法的执行是否会互相阻塞。即这两个方法可以在不同线程中并行执行吗?
I have class with 2 synchronized methods:
class Service {
public synchronized void calc1();
public synchronized void calc2();
}
Both takes considerable time to execute. The question is would execution of these methods blocks each other. I.e. can both methods be executed in parallel in different threads?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不它们不能在同一个服务上并行执行 - 两个方法共享同一个监视器(即
this
),因此如果线程 A 正在执行calc1
,线程 B 将无法获取监视器,因此无法运行calc2
。 (请注意,线程 B 可以在Service
的不同实例上调用任一方法,因为它将尝试获取不同的、未持有的监视器,因为this
所讨论的会有所不同。)最简单的解决方案(假设您希望它们独立运行)是使用显式监视器执行类似以下操作:
所讨论的“锁”不需要具有任何特殊功能不仅仅是对象,因此具有特定的监视器。如果您有更复杂的要求,可能涉及尝试立即锁定并回退,或查询谁拥有锁定,您可以使用实际的锁定 对象,但对于基本情况,这些简单的
Object
锁都很好。No they can't be executed in parallel on the same service - both methods share the same monitor (i.e.
this
), and so if thread A is executingcalc1
, thread B won't be able to obtain the monitor and so won't be able to runcalc2
. (Note that thread B could call either method on a different instance ofService
though, as it will be trying to acquire a different, unheld monitor, since thethis
in question would be different.)The simplest solution (assuming you want them to run independently) would be to do something like the following using explicit monitors:
The "locks" in question don't need to have any special abilities other than being Objects, and thus having a specific monitor. If you have more complex requirements that might involve trying to lock and falling back immediately, or querying who holds a lock, you can use the actual Lock objects, but for the basic case these simple
Object
locks are fine.是,您可以在两个不同的线程中执行它们,而不会弄乱您的类内部,但是否它们不会并行运行 - 每次只会执行其中一个。
Yes, you can execute them in two different threads without messing up your class internals but no they won't run in parallel - only one of them will be executed at each time.
不,他们不可能。在这种情况下,您可以使用
synchronized
块而不是同步整个方法。不要忘记在不同的对象上进行同步。No, they cannot be. In this case you might use a
synchronized
block instead of synchronizing the whole method. Don't forget to synchronize on different objects.