daily pastebin goal
83%
SHARE
TWEET

Untitled

a guest Dec 16th, 2018 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class ThreadCommunication {
  2. public static Queue<Integer> myQueue = new LinkedList<Integer>();
  3.  
  4. public static void main(String[] args) {
  5.  ProducerThread pthread = new ProducerThread(myQueue);
  6.  ConsumerThread cthread = new ConsumerThread(myQueue);
  7.  pthread.start();
  8.  cthread.start();
  9. }
  10. }
  11.  
  12. class ProducerThread extends Thread{
  13. public Queue<Integer> sharedQueue;
  14. public ProducerThread(Queue<Integer> sharedQueue){
  15.  this.sharedQueue = sharedQueue;
  16. }
  17. public void run(){
  18.  for(int i=0;i<10;i++){
  19.  synchronized (sharedQueue) {
  20.   try {
  21.   if(sharedQueue.size()>=1){
  22.    sharedQueue.wait();
  23.   }else{
  24.    sharedQueue.add(i);
  25.    System.out.println("Integer "+i+" is Produced");
  26.    sharedQueue.notifyAll();
  27.   }    
  28.   } catch (InterruptedException e) {
  29.     e.printStackTrace();
  30.   }
  31.   }
  32.  }
  33. }
  34. }
  35.  
  36. class ConsumerThread extends Thread{
  37.  public Queue<Integer> sharedQueue;
  38.  public ConsumerThread(Queue<Integer> sharedQueue){
  39.   this.sharedQueue = sharedQueue;
  40.  }
  41.  
  42.  public void run(){
  43.   synchronized (sharedQueue) {
  44.    
  45.  
  46.   while(true){
  47.    try {
  48.    if(sharedQueue.size()==0){
  49.      sharedQueue.wait();
  50.    }else{
  51.     int result = sharedQueue.poll();
  52.     System.out.println("Consumed Item is "+result);
  53.     sharedQueue.notifyAll();
  54.    }
  55.    
  56.    } catch (InterruptedException e) {
  57.     // TODO Auto-generated catch block
  58.     e.printStackTrace();
  59.    }
  60.    }
  61.   }
  62.  }
  63.  
  64. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top