title: Thread Locks and Condition Variables, The Producer Consumer Example
body: <p>I have to write this produce consumer application using multithreading. I wrote the following java code but havn;t been able to figure out where it is getting wrong. Also i want to know whether my class design is apt or if my coding style is appropriate.</p>
  
  <p>Thanks in Advance!!!</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I have modified the produce consumer code: But it still has some problem.</p>
  
  <pre><code>import java.util.*;
  import java.lang.Thread;
  
  public class pc_example {
  
  public static void main (String [] args) {
      Store store = new Store( 10 );
      produce p = new produce(store);
      consume c = new consume (store);
      p.start();
      c.start();
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>class Store {
  public Queue&lt;Integer&gt; Q;
  public int max_capacity;
  
  Store( int max_capacity ) {
      Q = new LinkedList&lt;Integer&gt;();
      this.max_capacity = max_capacity;
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>class produce extends Thread {
  
  private Store store;
  private int element;
  
  produce ( Store store ) {
      this.store = store;
      this.element = 0;
  }
  
  
  
  public void put() {
      synchronized (store) {
          if (store.Q.size() &gt; store.max_capacity) {
              try {
                  wait();
              } catch (InterruptedException e) {}
          }
          else {
              element ++;
              System.out.println( "Producer put: " + element );
              store.Q.add(element);
              notify();
          }               
      }           
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code>class consume extends Thread {
  private int cons;
  private Store store;
  
  consume (Store store) {
      this.store = store;
      this.cons = 0;
  }
  
  public void get() {
      synchronized (store) {
          if (store.Q.size() == 0) {
              try {
                  wait();
              } catch (InterruptedException e) {}
          }
          else {
              int a = store.Q.remove();
              System.out.println( "Consumer put: " + a );
              cons++;
  
              if (store.Q.size() &lt; store.max_capacity)
                  notify();
          }
      }
  }
  </code></pre>
  
  <p>}</p>