notify and notifyAll Who should use?

We should try to use notifyAll, because it is possible to use the notify signal loss occurs.

eg: wait timeout mode to achieve a connection pool:

Assuming wait a long time T, the current time is now + T after a timeout,


long overtime = now + T;
long remainTime = T;//等待的持续时间
while(remainTime>0 && result不满足条件){
    wait(remainTime);
    remainTime  = overtime - now;//等待剩余的持续时间    
}
return result;

join () method needs to pay attention to place: A thread, execute the join method thread B, thread A must wait after the completion of the implementation of B, A thread can continue their work

Call yield (), sleep (), wait (), notify () methods such as the impact on the lock?

Thread after executing yield () method, is not held by the lock release, sleep () method is called, is not held by the lock release, the lock must hold before calling the method, calling the wait () method after , the lock will be released when the wait () method returns, the thread that holds the lock again.

Before calling the method, you must hold the lock, call notify () method itself does not release the lock.

Released seven original articles · won praise 1 · views 326

Guess you like

Origin blog.csdn.net/baidu_36882394/article/details/103550023