Advertisement
Oppenheimer

MultiThreading 2 : wait() & notify()

Feb 24th, 2025
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.*;
  2.  
  3.  
  4. class Q {
  5.     int num;
  6.     boolean valueSet = false;
  7.     public  synchronized void set(int num){
  8.        
  9.         // wait for get to retrieve  before setting value again ..
  10.         while(valueSet){
  11.             try { wait(); } catch (Exception e){}
  12.         }
  13.         valueSet = true;
  14.         this.num = num;
  15.         System.out.println("set " +this.num);
  16.         notify();
  17.     }
  18.     public synchronized void get(){
  19.  
  20.         // wait for set to put value before getting it
  21.         while(valueSet == false){
  22.             try { wait(); } catch (Exception e){}
  23.         }
  24.         System.out.println("get " +this.num);
  25.         valueSet = false;
  26.         notify();
  27.     }
  28. }
  29.  
  30. class Producer implements Runnable{
  31.     Q q;
  32.  
  33.     public Producer(Q q){
  34.         this.q = q;
  35.         Thread t = new Thread(this, "Producer");
  36.         t.start();
  37.     }
  38.  
  39.     public void run(){
  40.         int i=0;
  41.         while(true){
  42.             q.set(i++);
  43.             try{
  44.                 Thread.sleep(100);
  45.             }catch(Exception e){
  46.  
  47.             }
  48.         }
  49.     }
  50. }
  51.  
  52. class Consumer implements Runnable{
  53.     Q q;
  54.  
  55.     Consumer(Q q){
  56.         this.q =q;
  57.         Thread t = new Thread(this, "Consumer");
  58.         t.start();
  59.     }
  60.  
  61.     public void run(){
  62.         while(true){
  63.             q.get();
  64.             try{
  65.                 Thread.sleep(1000);
  66.             }catch(Exception e){
  67.  
  68.             }
  69.         }
  70.     }
  71.  
  72. }
  73.  
  74. public class Main{
  75.     public static void main(String args[]) throws Exception{
  76.         Q q = new Q();
  77.         new Producer(q);
  78.         new Consumer(q);
  79.         /*  here producer can produce faster than consumer can consume so
  80.             we make producer wait till consumer sets flag to false ..
  81.             and vice versa
  82.         */
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement