package _procon;
public class Table {
private final String[] buffer;
private int tail;
private int head;
private int count;
public Table(int size)
{
this.buffer = new String[size];
this.head = 0;
this.tail = 0;
this.count = 0;
}
public synchronized void put(String cake) throws InterruptedException
{
System.out.println(Thread.currentThread().getName()+" puts "+ cake);
while(count>=buffer.length)
{
wait();
}
buffer[tail] = cake;
tail = (tail+1)%buffer.length;
count++;
notifyAll();
}
public synchronized String get() throws InterruptedException
{
while(count<=0)
{
wait();
}
String cake = buffer[head];
head = (head+1)%buffer.length;
count--;
System.out.println(Thread.currentThread().getName()+" takes "+cake);
notifyAll();
return cake;
}
}
package _procon;
import java.util.Random;
public class MakerThread extends Thread {
private Random random;
private final Table table;
private static int id = 0;
public MakerThread(String name,Table table,Random random)
{
super(name);
this.random = random;
this.table = table;
}
@Override
public void run()
{
try {
while(true)
{
Thread.sleep(random.nextInt(1000));
String cake = "[Cake No. "+nextId()+" By "+getName()+" ]";
table.put(cake);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static synchronized int nextId()
{
return id++;
}
}