gpt4 book ai didi

java - 有界缓冲区死锁

转载 作者:行者123 更新时间:2023-12-01 13:11:48 37 4
gpt4 key购买 nike

我尝试用 Java 编写一个简单的有界缓冲区,但在前几次操作后程序似乎陷入了僵局。

public BoundedBuffer(int size){
buffer = new LinkedList<E>();
this.empty = new Semaphore(size);
this.full = new Semaphore(0);
this.mutex = new Semaphore(1);
}

public void produce(E element) throws InterruptedException {
this.empty.acquire();
this.mutex.acquire();
this.buffer.add(element);
this.mutex.release();
this.full.release();

}

public E consume() throws InterruptedException{
this.full.acquire();
this.mutex.acquire();
E elem = this.buffer.remove(0);
this.mutex.release();
this.full.release();
return elem;
}

这些是我的生产和消费方法,它们应该避免死锁。然而程序总是挂起。我错过了什么吗?

编辑:还添加了我的构造函数。

最佳答案

我认为您可能对 this.empty.acquire() 有问题,并且从未调用 this.empty.release()。最终empty将耗尽许可证。

关于java - 有界缓冲区死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800120/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com