Commit 05721e19 authored by Mohamad Bashar Desoki's avatar Mohamad Bashar Desoki

Producer Consumer Example

parent 172ae79c
......@@ -5,7 +5,9 @@
* Race Condition
* Critical Section
* Memory inconsistency
*
* ParkingCash Example
* ProducerConsumer Example
* synchronized, wait, notify, notifyAll keyword
* Locks and Atomic Variables
*Useful Links*
......
package ProducerConsumer;
public class Consumer implements Runnable{
private EventStorage storage;
public Consumer(EventStorage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i=0; i<100; i++){
storage.get();
}
}
}
package ProducerConsumer;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
public class EventStorage {
private int maxSize;
private Queue<Date> storage;
public EventStorage() {
maxSize = 10;
storage = new LinkedList<>();
}
public synchronized void set(){
while (storage.size()==maxSize){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.offer(new Date());
System.out.printf("Set: %d",storage.size());
notify();
}
public synchronized void get(){
while (storage.size()==0){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String element=storage.poll().toString();
System.out.printf("Get: %d: %s\n",storage.size(),element);
notify();
}
}
package ProducerConsumer;
public class Main {
public static void main(String[] args) {
EventStorage storage = new EventStorage();
Producer producer = new Producer(storage);
Thread thread1 = new Thread(producer);
Consumer consumer = new Consumer(storage);
Thread thread2 = new Thread(consumer);
thread2.start();
thread1.start();
}
}
package ProducerConsumer;
public class Producer implements Runnable{
private EventStorage storage;
public Producer(EventStorage storage){
this.storage=storage;
}
@Override
public void run() {
for (int i=0; i<100; i++){
storage.set();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment