Класс очереди
Код: Выделить всё
class BoundedQueue {
private Queue q;
int maxSize;
Semaphore produce;
Semaphore consume;
BoundedQueue(int size) throws InterruptedException {
maxSize = size;
q = new LinkedList();
produce = new Semaphore(maxSize);
consume = new Semaphore(-1);
}
void push(int val) {
try {
produce.acquire();
q.offer(val);
System.out.println(Thread.currentThread().getName() + " produced " + val);
if (q.size() > maxSize) {
System.out.println("Max size breached");
}
consume.release();
}
catch (InterruptedException e) {
System.out.println("Interrupted exception " + e);
produce.release();
}
}
int pop() {
int val = -1;
try {
consume.acquire();
if (q.isEmpty()) {
System.out.println(Thread.currentThread().getName() + " is trying to consume empty queue");
return val;
}
val = q.remove();
System.out.println(Thread.currentThread().getName() + " consumed " + val);
if (q.size() > maxSize) {
System.out.println("Max size breached");
}
produce.release();
}
catch (InterruptedException e) {
System.out.println("Interrupted exception " + e);
consume.release();
}
return val;
}
}
Код: Выделить всё
public class ProducerConsumerSemaphores extends Thread {
private BoundedQueue que;
private String workerType;
ProducerConsumerSemaphores(BoundedQueue que, String workerType) {
this.que = que;
this.workerType = workerType;
}
public void run() {
System.out.println("Starting worker " + workerType + " " + Thread.currentThread().getName());
if (workerType.equals("producer")) {
Random rand = new Random();
int val = rand.nextInt(1, 100);
for (int i=0; i
Подробнее здесь: [url]https://stackoverflow.com/questions/78785767/producer-consumers-using-semaphores[/url]
Мобильная версия