There is no condition in the accepted answer. Whenever you wait, you should always check the condition to protect yourself from side awakening. In principle, the expectation is guaranteed to return normally in all cases of which he speaks. He may also return for no apparent reason. You must follow the pattern from Javadoc . I would not recommend catching Throwable here or almost everywhere. Instead, catch only an InterruptedException. In addition, you must ensure that the status check is thread safe. So, for example, you can do the following:
private boolean condition; private Object lock = new Object(); private long timeout = 1000; public void conditionSatisfied() { synchronized (lock) { condition = true; lock.notify(); } } public void awaitCondition() { synchronized (lock) { while (!condition) { try { lock.wait(timeout); } catch (InterruptedException e) {
You will notice that you are waiting in a loop. A timeout simply means that you will wait at intervals until the timeout value. If you want to set a common timeout limit, you must mark the current time outside the loop and check it after each wait.
source share