1
0
mirror of https://github.com/robindhole/fundamentals.git synced 2025-03-16 19:30:11 +00:00

Uses synchronised keyword.

This commit is contained in:
Tanmay 2022-08-24 13:44:58 +01:00
parent 4f751a011e
commit c7437d90bc
4 changed files with 18 additions and 16 deletions
os/code/os
src/main/java/com/scaler/producerconsumer
target/classes/com/scaler/producerconsumer

@ -12,15 +12,16 @@ public class Consumer implements Runnable {
private Queue<UnitOfWork> store; private Queue<UnitOfWork> store;
private String name; private String name;
@Override @Override
public void run() { public void run() {
while (true) { while (true) {
synchronized (store) {
if (store.size() > 0) { if (store.size() > 0) {
store.remove(); store.remove();
System.out.println("Consumed: " + name + " Left units :" + store.size()); System.out.println("Consumed: " + name + " Left units :" + store.size());
} }
} }
}
} }

@ -13,15 +13,16 @@ public class Producer implements Runnable {
private int maxSize; private int maxSize;
private String name; private String name;
@Override @Override
public void run() { public void run() {
while (true) { while (true) {
synchronized (store) {
if (store.size() < maxSize) { if (store.size() < maxSize) {
store.add(new UnitOfWork()); store.add(new UnitOfWork());
System.out.println("Produced: " + name + " Left units :" + store.size()); System.out.println("Produced: " + name + " Left units :" + store.size());
} }
} }
}
} }