Difference between Synchronized block with wait/notify and without them?
If I just use synchronized, not wait/notify method, will it still keep thread-safe ?
What's the difference ?
Thx in advance.
Using synchronized
makes a method / block accessible by only on thread at a time. So, yes, it's thread-safe.
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.
so after just being embarrassed in an interview question on this I decided to look it up and understand it again for 1 billionth time lol.
synchronized block makes the code thread safe. No doubt about that. When wait() and notify() or notifyAll() come in is where your trying to write more efficient code. For example if you have a list of items that multiple threads share then if u put it in synchronized block of a monitor then threads threads will constantly jump in and run the code back and forth, back and fort during context switches......even with an empty list!
The wait() is hence used on the monitor (the object inside the synchronized(..)) as a mechanism to to tell all threads to chill out and stop using cpu cycles until further notice or notifyAll().
so something like:
synchronized(monitor) {
if( list.isEmpty() )
monitor.wait();
}
...somewhere else...
synchronized(monitor){
list.add(stuff);
monitor.notifyAll();
}
Effective Java item 69: "Given the difficulty of using wait and notify correctly, you should use the higher-level concurrency utilities instead."
Avoid using wait() and notify(): use synchronized
, or other utilities from java.util.concurrent, when possible.
上一篇: 为什么对象可以改变类变量的值?