aakash2310

PC.java

Feb 18th, 2022
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. class PC
  2. {
  3.     public static void main(String args[])
  4.     {
  5.         Q q = new Q();
  6.         Producer p = new Producer(q);
  7.         Consumer c = new Consumer(q);
  8.         System.out.println("Press Control-C to stop.");
  9.     }
  10. }
  11. class Q
  12. {
  13.     int n;
  14.     boolean valueSet = false;
  15.     synchronized int get()
  16.     {
  17.         if(!valueSet)
  18.             try
  19.             {
  20.                     wait();
  21.             }
  22.             catch(Exception e)
  23.             {
  24.  
  25.             }
  26.             System.out.println("Got: " + n);
  27.             valueSet = false;
  28.             notify();
  29.             return n;
  30.     }
  31.     synchronized void put(int n)
  32.     {
  33.         if(valueSet)
  34.         try
  35.         {
  36.             wait();
  37.         }
  38.         catch(Exception e)
  39.         {
  40.  
  41.         }
  42.         this.n = n;
  43.         valueSet = true;
  44.         System.out.println("Put: " + n);
  45.         notify();
  46.     }
  47. }
  48.  
  49. class Producer implements Runnable
  50. {
  51.     Q q;
  52.     Thread t;
  53.     Producer(Q q)
  54.     {
  55.         this.q = q;
  56.  
  57.         t = new Thread(this, "Producer");
  58.         t.start();
  59.     }
  60.     public void run()
  61.     {
  62.         int i = 0;
  63.         while(true)
  64.         {
  65.             q.put(i++);
  66.         }
  67.     }
  68. }
  69.  
  70. class Consumer implements Runnable
  71. {
  72.     Q q;
  73.     Consumer(Q q)
  74.     {
  75.         this.q = q;
  76.         new Thread(this, "Consumer").start();
  77.     }
  78.     public void run()
  79.     {
  80.         while(true)
  81.         {
  82.             q.get();
  83.         }
  84.     }
  85. }
  86.  
  87.  
Advertisement
Add Comment
Please, Sign In to add comment