Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PC
- {
- public static void main(String args[])
- {
- Q q = new Q();
- Producer p = new Producer(q);
- Consumer c = new Consumer(q);
- System.out.println("Press Control-C to stop.");
- }
- }
- class Q
- {
- int n;
- boolean valueSet = false;
- synchronized int get()
- {
- if(!valueSet)
- try
- {
- wait();
- }
- catch(Exception e)
- {
- }
- System.out.println("Got: " + n);
- valueSet = false;
- notify();
- return n;
- }
- synchronized void put(int n)
- {
- if(valueSet)
- try
- {
- wait();
- }
- catch(Exception e)
- {
- }
- this.n = n;
- valueSet = true;
- System.out.println("Put: " + n);
- notify();
- }
- }
- class Producer implements Runnable
- {
- Q q;
- Thread t;
- Producer(Q q)
- {
- this.q = q;
- t = new Thread(this, "Producer");
- t.start();
- }
- public void run()
- {
- int i = 0;
- while(true)
- {
- q.put(i++);
- }
- }
- }
- class Consumer implements Runnable
- {
- Q q;
- Consumer(Q q)
- {
- this.q = q;
- new Thread(this, "Consumer").start();
- }
- public void run()
- {
- while(true)
- {
- q.get();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment