gpt4 book ai didi

java - 当我们在消费者和生产者缓冲区中使用信号量时

转载 作者:行者123 更新时间:2023-12-01 19:26:06 28 4
gpt4 key购买 nike

我正在消费者和生产者中研究 BoundedBuffer 类,我们希望在该类中使用信号量我们这样做了,但是每次使用 acquire() 时都会出现错误错误是:

未报告的异常 java.lang.InterruptedException;必须被捕获或宣布被抛出

这是代码:

import java.util.concurrent.Semaphore;

public class BoundedBuffer implements Buffer {
private static final int BUFFER_SIZE = 4;

/**
* volatile does not appear in the printed text. A discussion of
* volatile is in chapter 7.
*/
private volatile int count;
private Object[] buffer;
private int in; // points to the next free position in the buffer
private int out; // points to the next full position in the buffer

private Semaphore mutex;
private Semaphore empty;
private Semaphore full;

public BoundedBuffer() { //constractur
// buffer is initially empty
//count = 0;
in = 0;
out = 0;

buffer = new Object[BUFFER_SIZE];

mutex = new Semaphore(1);
empty = new Semaphore(BUFFER_SIZE);
full = new Semaphore(0);
}

// producer calls this method
public void insert(Object item) {
//while (count == BUFFER_SIZE)
// ; // do nothing the brach full

// add an item to the buffer
// ++count;

empty.acquire();
mutex.acquire();
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;//that to do cyrcle or to go to the begining againe
/*
if (count == BUFFER_SIZE)
System.out.println("Baker put " + item + " Shelf FULL");
else
System.out.println("Baker put " + item + " Shelf Size = " + count);
*/


mutex.release();
full.release();

}

// consumer calls this method
public Object remove() {
//Object item;
full.acquire();
mutex.acquire();

//while (count == 0)
; // do nothing the buffer is empty

// remove an item from the buffer
//--count;

Object item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
mutex.release();
empty.release();
return item;
}
}

最佳答案

也许我不完全理解你的应用程序,但你不能只使用 java.util.concurrent 包中已经提供的有界缓冲区类( ArrayBlockingQueue )吗?

This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be increased. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will similarly block.

关于java - 当我们在消费者和生产者缓冲区中使用信号量时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/847384/

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