How can I make a thread wait without releasing the lock ? If this is not possible, then how can I pause a thread while a certain condition is not met and unpause it as soon the condition is met or when I notify it
Waiting/Notifying can only be done in the scope of a lock (eg a synchronized method or synchronized block).
Both the wait
and notify
should synchronize on the same object.
The waiting thread:
synchronized(lockObject) {
lockObject.wait(); <-- it will wait here until the notify is called.
}
The notifying thread:
synchronized(lockObject) {
lockObject.notify();
}
The lockObject can be anything. It could just be a new Object()
, but very often it could be some collection, a logical object that represents a printer, ... anything.
Hint: Judging from the comments section, you may need the following: The notify
releases just one waiting thread. But you could actually have multiple threads waiting. If you want to release all of them, use notifyAll
.
Alternatively, you could create a class, and use method level locking.
class LockObject {
public synchronized void waitMethod() {
wait();
}
public synchronized void notifyMethod() {
notify();
}
}
Again both have to use the same object to lock on.
LockObject instance = new LockObject();
Then the waiting thread:
instance.waitMethod();
And the notifying thread:
instance.notifyMethod();
Also take a look inside the concurrency
packages and tutorials of the JDK , and you will find more advanced locking objects. Just to name one, countdown latches are powerful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.