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