Monday, 13 July 2015

Java Programs[Important]

  1. WRITE A JAVA PROGRAM that correctly implements Producer-Consumer problem using the concept of Inter Thread Communication.
  2.  
  3. Program :
  4.  
  5. class Q 
  6. int n; 
  7. boolean valueSet = false;
  8.  
  9. synchronized int get() 
  10. {
  11.  if (!valueSet) 
  12. try 
  13. wait();
  14.  } 
  15. catch (InterruptedException e)
  16.  {
  17.  }
  18.  
  19. System.out.println(“Got: “ + n);
  20.  valueSet = false;
  21.  notify();
  22.  return n;
  23.  }
  24.  
  25. synchronized void put(int n) 
  26. if (valueSet)
  27.  try 
  28. {
  29.  wait();
  30.  } 
  31. catch (InterruptedException e)
  32.  { 
  33. }
  34.  
  35. this.n = n;
  36.  valueSet = true;
  37.  System.out.println(“Put: “ + n);
  38.  notify();
  39.  }
  40.  }
  41.  
  42. class Producer implements Runnable {
  43.  Q q;
  44.  
  45. Producer(Q q) 
  46. this.q = q;
  47.  new Thread(this, “Producer”).start(); 
  48. }
  49. public void run() { int i = 0;
  50.  
  51. while(true) { q.put(i++); 
  52. }
  53.  }
  54.  }
  55.  
  56. class Consumer implements Runnable {
  57.  Q q;
  58.  
  59. Consumer(Q q)
  60.  {
  61.  this.q = q; 
  62. new Thread(this, “Consumer”).start(); 
  63. }
  64.  
  65. public void run() 
  66. while(true) 
  67. q.get(); 
  68. }   

  69. }
  70.  
  71. class PC 
  72. {
  73.  public static void main (String args[ ])
  74.  { 
  75. Q q = new Q();
  76.  new Producer(q);
  77.  new Consumer(q);
  78.  
  79. System.out.println(“Press Ctrl-C to stop”);
  80.  } 
  81. }