我正在尝试在Java中实现有限缓冲区,以了解有关并发的更多信息。几个线程将使用add()和remove()方法访问此缓冲区。我正在使用三个信号量来实现这一点(一个用于数量可利用的项目,一个用于空间可利用的空间,以及用于关键部分的二进制信号量)。当缓冲区已满/空时,我想分别打印“ buffer full”或“ buffer empty”。
在调用信号量中的wait()之前,我已经将print语句设置为full / empty。但是,这似乎在错误的时间打印了满/空的数量,远远超过了应有的数量。我认为这是在错误的时间进行上下文切换。我应该更改打印声明的位置吗?
我的Semaphore
类可以使用prtstmt参数打印完整/空白
public class Semaphore {
private String prtstmt;
private int count;
public semaphore(String prtstmt, int count) {
this.count = count;
this.prtstmt = prtstmt;
}
public synchronized void V(){
count = count + 1;
notify();
}
public synchronized void P(){
count = count - 1;
if (count < 0) {
System.out.println(prtstmt);
wait();
}
}
}
有界缓冲区
public class BoundedBufferUsingSemaphore {
private static final int SIZE = 10;
public static void main(String[] args) {
Semaphore full = new Semaphore(0, "Buffer full!");
Semaphore empty = new Semaphore(SIZE, "Buffer Empty!");
Semaphore mutex = new Semaphore(1, null);
Vector<Integer> sQueue = new Vector<Integer>();
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5000; i++) {
empty.p();
mutex.p();
System.out.println(Thread.currentThread().getName() + " is trying to insert item " + i);
sQueue.add(i);
mutex.v();
full.v();
}
}
});
Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
full.p();
mutex.p();
System.out.println(Thread.currentThread().getName() + " consuming item " + sQueue.remove(0));
mutex.v();
empty.v();
}
}
});
producerThread.setName("Producer");
consumerThread.setName("Consumer");
consumerThread.start();
producerThread.start();
}
}
示例输出如下
Consumer consuming item 5
Buffer empty!
Producer is trying to insert item 6
Producer is trying to insert item 7
Consumer consuming item 6
Producer is trying to insert item 7
Consumer consuming item 6
Buffer empty!
Consumer consuming item 5
Buffer empty!
Producer is trying to insert item 6
Producer is trying to insert item 7
Consumer consuming item 6
答案 0 :(得分:0)
本地信号量会执行以下操作!
boolean acquired = semaphore.tryAcquire();
if (acquired) {
System.out.println("Got it!");
semaphore.release();
} else {
System.out.println("Returned immediately, would have blocked");
}