lock中类似wait和notify的方法:
await和signal/signalAll
原理:lock中使用Condition类做为锁监视器,调用Condition的await()和signal()实现线程的等待和唤醒。
实现代码:
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();
lock.lock();
try{
while(...){
condition.await();
}
condition.signalAll();
}catch(Exception e){
}finally{
lock.unlock();
}
和wait/notifyAll相比的好处:
能够精准的唤醒指定的线程
多线程按顺序执行的实现:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class OrderThread {
public static void main