阻塞等待模式
线程执行任务时条件不满足时挂起阻塞 等待条件满足时执行对应任务
实例:
public class GuardedQueue {
// 定义存放Integer类型的queue
private final LinkedList<Integer> queue = new LinkedList<>();
// 定义队列的最大容量
private final int LIMIT = 100;
// 向queue中插入数据 当queue的元素数量大于最大容量,则会阻塞
public void off(Integer data) throws InterruptedException{
synchronized (this){
// 判断queue的元素个数是否大于最大容量
while (queue.size() >= LIMIT){
// 阻塞
this.wait();
}
// 没有则将数据放进queue
queue.addLast(data);
// 再唤醒阻塞休息室的线程
this.notifyAll();
}
}
// 获取queue中的元素 没有则阻塞等待queue中有有元素为止
public Integer take() throws InterruptedException{
synchronized (this){
// 判断队列为空 阻塞
while (queue.isEmpty()){
this.wait();
}
// 不为空 取数据
Integer first = queue.removeFirst();
this.notifyAll();
return first;
}
}
}
总结
这种模式是一种多线程基本的应用,使用Object类的wait()方法和notifyAll()方法来实现阻塞和唤醒执行。