added ex O

This commit is contained in:
Louis Heredero 2024-12-17 13:40:19 +01:00
parent f2bb16ea85
commit 1255f304fc
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
4 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,51 @@
package exercises.ex_o;
import java.util.Stack;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class LockedWithConditionsStack {
private final int capacity;
private final Stack<Integer> stack = new Stack<>();
private final ReentrantLock lock = new ReentrantLock();
private final Condition fullCondition = lock.newCondition();
private final Condition emptyCondition = lock.newCondition();
public LockedWithConditionsStack(int capacity) {
this.capacity = capacity;
}
public void pushToStack(int value) {
try {
lock.lock();
while (stack.size() == capacity) {
System.out.println("Stack is full, waiting until someone pops");
fullCondition.await();
}
stack.push(value);
emptyCondition.signalAll();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
public int popFromStack() {
int value;
try {
lock.lock();
while (stack.isEmpty()) {
System.out.println("Stack is empty, waiting until someone pushes");
emptyCondition.await();
}
value = stack.pop();
fullCondition.signalAll();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
return value;
}
}

View File

@ -0,0 +1,16 @@
package exercises.ex_o;
public class NumberConsumer implements Runnable {
private LockedWithConditionsStack stack;
public NumberConsumer(LockedWithConditionsStack stack) {
this.stack = stack;
}
@Override
public void run() {
while (true) {
System.out.println("Pop from stack: " + stack.popFromStack());
}
}
}

View File

@ -0,0 +1,17 @@
package exercises.ex_o;
public class NumberProducer implements Runnable {
private LockedWithConditionsStack stack;
public NumberProducer(LockedWithConditionsStack stack) {
this.stack = stack;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("Pushing to stack " + i + "...");
stack.pushToStack(i);
System.out.println("Pushed to stack " + i);
}
}
}

View File

@ -0,0 +1,9 @@
package exercises.ex_o;
public class TestingReentrantLockWithConditions {
public static void main(String[] args) {
LockedWithConditionsStack stack = new LockedWithConditionsStack(5);
(new Thread(new NumberProducer(stack))).start();
(new Thread(new NumberConsumer(stack))).start();
}
}