I have written a water cooler example in which the consumer drinks from the water cooler until it's empty and when it gets empty the producer fills it up. The consumers wait until it's filled up and then start drinking again. Can you please review?
Producer
package com.par.consumer.producer;
import java.util.List;
public class Producer implements Runnable {
private List<Integer> mySharedList;
int size;
public Producer(List<Integer> sharedList,int size) {
this.mySharedList=sharedList;
this.size=size;
}
@Override
public void run() {
while(true)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (mySharedList) {
System.out.println("Size is "+mySharedList.size());
if(mySharedList.isEmpty()) // Water cooler is empty fill it up
{
for(int i=1;i<=size;i++){
System.out.println("Adding water "+i);
mySharedList.add(i);
}
mySharedList.notify();
}
try {
System.out.println("Producer waiting");
mySharedList.wait();
System.out.println("Producer waiting exit");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Consumer
package com.par.consumer.producer;
import java.util.List;
public class Consumer implements Runnable{
private List<Integer> mySharedList;
public Consumer(List<Integer> sharedList) {
this.mySharedList=sharedList;
}
@Override
public void run() {
while(true)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (mySharedList) {
if(mySharedList.isEmpty())
{
System.out.println("IS EMPTY");
try {
mySharedList.notify();
System.out.println("Consumer waiting");
mySharedList.wait();
System.out.println("Consumer waiting exit");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Drinking "+mySharedList.remove(0));
}
}
}
}
WaterCooler (Driver)
package com.par.consumer.producer;
import java.util.ArrayList;
import java.util.List;
public class WaterCooler {
volatile List<Integer> list=new ArrayList<Integer>();
public static void main(String[] args) {
new WaterCooler().run();
}
void run()
{
new Thread(new Producer(list, 4)).start();
new Thread(new Consumer(list)).start();
}
}