When we are using wait and notify in thread environment. I have a class to process data as background process. And when there is no data to process it should call wait.
synchronized(some_object){
wait();
}
In another class I am adding the data again. I need call notify() method.
synchronized(some_object){
runnabale_object.notify();
}
Why i should use same object for synchronized block in those two different class. As i read synchronize is used to
The "Synchronized" keywords prevents concurrent access to a block of code or object by multiple Threads.
But these two are different block. But i can understand the problem when we use multiple threads. While one thread block other can call notify before the same thread call notify.
My Questions
- Can we use different lock objects (synchronized(object)) for single threaded environment?
- Best way of use same lock object when we have wait and notify in different classes?
waitandnotifyon the lock object (in your casesome_object.wait()andsome_object.notify())!wait/notifythen the waiting/notifyingThreadmust own the monitor of theObjectit is operating on. This also answers your question, you must use the same object forsynchronizingas forwait/notify.