Skip to content

Instantly share code, notes, and snippets.

@tacksoo
Created February 5, 2013 05:51
Show Gist options
  • Save tacksoo/4712535 to your computer and use it in GitHub Desktop.
Save tacksoo/4712535 to your computer and use it in GitHub Desktop.
The famous producer/consumer example
public class Consumer extends Thread {
private IntBuffer buffer;
public Consumer(IntBuffer buffer)
{
this.buffer = buffer;
}
public void run() {
while (true)
{
int num = buffer.remove();
System.out.println("Consumer " + num);
}
}
}
public class IntBuffer {
private int index;
private int[] buffer = new int[10];
public synchronized void add(int num)
{
while (index == buffer.length - 1)
{
try {
wait();
} catch (InterruptedException e)
{
}
}
buffer[index++] = num;
notifyAll();
}
public synchronized int remove()
{
while (index == 0)
{
try {
wait();
} catch (InterruptedException e)
{
}
}
int ret = buffer[--index];
notifyAll();
return ret;
}
}
public class Producer extends Thread {
private IntBuffer buffer;
public Producer(IntBuffer buffer) {
this.buffer = buffer;
}
public void run() {
Random r = new Random();
while (true) {
int num = Math.abs(r.nextInt() % 100);
buffer.add(num);
System.out.println("Produced " + num);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment