/**
* 要做一下异常处理 原理 synchronized和wait/notify 线程堵塞锁 可阻塞队列
* @author zw
*
*/
public class BoundedBuffer_Synchronized {
private Object[] items = new Object[2];
private Object notEmpty = new Object();
private Object notFull = new Object();
int count,putidx,takeidx;
//压入
public void put(Object obj) throws InterruptedException{
synchronized(notFull){
while(count == items.length){
notFull.wait();
}
}
items[putidx] = obj;
if(++putidx == items.length){
putidx = 0;
}
count ++;
synchronized (notEmpty) {
notEmpty.notify();
}
}
public Object take() throws InterruptedException{
synchronized(notEmpty){
while(count == 0){
notEmpty.wait();
}
}
Object x = items[takeidx];
System.out.println("取第"+takeidx+"个元素"+x);
if(++takeidx == ite
可阻塞队列 synchronized和wait/notify 线程堵塞锁
最新推荐文章于 2023-02-11 13:07:54 发布
本文介绍了如何使用`synchronized`关键字和`wait/notify`机制来实现一个可阻塞队列`BoundedBuffer_Synchronized`。在队列满时,`put`操作会阻塞,等待队列空出空间;队列空时,`take`操作同样会阻塞,直到有元素被放入。通过异常处理确保线程安全,同时在元素入队和出队时通知等待的线程。
摘要由CSDN通过智能技术生成