Created
February 5, 2013 05:51
-
-
Save tacksoo/4712535 to your computer and use it in GitHub Desktop.
The famous producer/consumer example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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