Advertisement
gitman3

Thread prod consume

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