Created
June 3, 2015 15:47
-
-
Save beoliver/d7874e43f6bd022be98b to your computer and use it in GitHub Desktop.
consume
This file contains hidden or 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
| import java.util.Random; | |
| /** | |
| * Created by boliver on 03/06/15. | |
| */ | |
| public class Main { | |
| public static void main(String args[]) { | |
| Container value = new Container(); | |
| Thread producer1 = new Thread(new Producer(1, value)); | |
| Thread producer2 = new Thread(new Producer(2, value)); | |
| Thread consumer1 = new Thread(new Consumer(1, value)); | |
| Thread consumer2 = new Thread(new Consumer(2, value)); | |
| producer1.start(); | |
| producer2.start(); | |
| consumer1.start(); | |
| consumer2.start(); | |
| } | |
| } | |
| class Container { | |
| private int value; | |
| private boolean hasUnreadValue = false; | |
| private Object lock = new Object(); | |
| public void add(int x) throws InterruptedException { | |
| synchronized (lock) { | |
| while (hasUnreadValue) { | |
| lock.wait(); | |
| } | |
| lock.notifyAll(); | |
| hasUnreadValue = true; | |
| value = x; | |
| } | |
| } | |
| public int get() throws InterruptedException { | |
| synchronized (lock) { | |
| while (!hasUnreadValue) { | |
| lock.wait(); | |
| } | |
| lock.notifyAll(); | |
| hasUnreadValue = false; | |
| return value; | |
| } | |
| } | |
| } | |
| class Producer implements Runnable { | |
| int id; | |
| Container value; | |
| public Producer(int id, Container value) { | |
| this.id = id; | |
| this.value = value; | |
| } | |
| public void run() { | |
| Random rand = new Random(); | |
| for (int i = 0; i < 10; i++) { | |
| int r = rand.nextInt(10); | |
| System.out.println("called from Producer #" + id + " ... random value is: " + r); | |
| try { | |
| value.add(r); | |
| } catch (InterruptedException e) {} | |
| } | |
| } | |
| } | |
| class Consumer implements Runnable { | |
| int id; | |
| Container value; | |
| public Consumer(int id, Container value) { | |
| this.id = id; | |
| this.value = value; | |
| } | |
| public void run() { | |
| for (int i = 0; i < 10; i++) { | |
| try { | |
| int v = value.get(); | |
| System.out.println("called from Consumer #" + id + " ... container value is : " + v); | |
| } catch (InterruptedException e) {} | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment