同步块与等待/通知和没有它们之间的区别? [英] Difference between Synchronized block with wait/notify and without them?
问题描述
如果我只使用synchronized,而不是wait / notify方法,它是否仍然保持线程安全?
If I just use synchronized, not wait/notify method, will it still keep thread-safe ?
有什么区别?
提前Thx。
推荐答案
使用 synchronized
使方法/块一次只能在线程上访问。所以,是的,它是线程安全的。
Using synchronized
makes a method / block accessible by only on thread at a time. So, yes, it's thread-safe.
这两个概念是组合在一起的,而不是相互排斥的。当您使用 wait()
时,您需要拥有该对象上的监视器。所以你需要在它之前有 synchronized(..)
。使用 .wait()
使当前线程停止,直到另一个线程在它等待的对象上调用 .notify()
。这是对 synchronized
的补充,它只确保只有一个线程将进入块/方法。
The two concepts are combined, not mutually-exclusive. When you use wait()
you need to own the monitor on that object. So you need to have synchronized(..)
on it before that. Using .wait()
makes the current thread stop until another thread calls .notify()
on the object it waits on. This is an addition to synchronized
, which just ensures that only one thread will enter a block/method.
这篇关于同步块与等待/通知和没有它们之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!