Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. class PC
  2. {
  3.   public static void main()
  4.   {
  5.     Q q = new Q();
  6.     new Producer(q);
  7.     new Consumer(q);
  8.     try { Thread.sleep(5000); } catch(InterruptedException e) {} ;    
  9.     q.work = false;
  10.   }
  11. }
  12. class Q
  13. {
  14.   int n;
  15.   boolean valueSet = false;
  16.   boolean work = true;  
  17.   synchronized int get()
  18.   {
  19.     if (!valueSet) try { wait(); }
  20.     catch(InterruptedException e) {} ;
  21.     int sum=0;
  22.     sum +=n;
  23.     System.out.println("Got: " + sum);
  24.     valueSet = false;
  25.     notify();
  26.     return n;      
  27.   }
  28.   synchronized void put(int n)
  29.   {
  30.     if (valueSet) try { wait(); }
  31.     catch(InterruptedException e) {} ;
  32.     this.n = n;
  33.     System.out.println("Put: " + n);
  34.     valueSet = true;      
  35.     notify();
  36.   }
  37. }
  38. class Producer implements Runnable
  39. {
  40.   Q q;
  41.   Producer(Q q)
  42.   {
  43.     this.q = q; new Thread(this, "Producer").start();
  44.   }
  45.   public void run()
  46.   {
  47.     int i = 1;  while (q.work) { q.put(i++); }
  48.   }
  49. }
  50. class Consumer implements Runnable
  51. {
  52.   Q q;
  53.   Consumer(Q q)
  54.   {
  55.     this.q = q;
  56.     new Thread(this, "Consumer").start();
  57.   }
  58.   public void run()
  59.   {
  60.     while (q.work) { q.get(); }
  61.   }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement