Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Thread example: Producer-Consumer in Java, 3 versions Java code example - Click here to copy ->>>

   Can't find what you're looking for? Try our search:

Really working examples categorized by API, package, class. You can compile and run our examples right away! Not from source code for Java projects - only working examples! Copy, compile and run!
------------------

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: ProdCons1.java,v 1.5 2004/02/09 03:34:07 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    do*****entation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by Ian F. Darwin.
 * 4. Neither the name of the author nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 
 * Java, the Duke mascot, and all variants of Sun's Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun's, and James Gosling's,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.util.*;
import java.io.*;

/** Producer-Consumer in Java. Version 1.
 */
public class ProdCons1 {

  protected LinkedList list = new LinkedList();

  protected void produce() {
    int len = 0;
    synchronized(list) {
      Object justProduced = new Object();
      list.addFirst(justProduced);
      len = list.size();
      list.notifyAll();
    }
    System.out.println("List size now " + len);
  }

  protected void consume() {
    Object obj = null;
    int len = 0;
    synchronized(list) {
      while (list.size() == 0) {
        try {
          list.wait();
        catch (InterruptedException ex) {
          return;
        }
      }
      obj = list.removeLast();
      len = list.size();
    }
    System.out.println("Consuming object " + obj);
    System.out.println("List size now " + len);
  }

  public static void main(String[] argsthrows IOException {
    ProdCons1 pc = new ProdCons1();
    System.out.println("Ready (p to produce, c to consume):");
    int i;
    while ((i = System.in.read()) != -1) {
      char ch = (char)i;
      switch(ch) {
        case 'p':  pc.produce()break;
        case 'c':  pc.consume()break;
      }
    }
  }
}
/**
* Java Code from Java Cookbook, Second Edition
* By Ian F. Darwin
* Second Edition June 2004
* Series: Cookbooks
* ISBN: 0-596-00701-9
* Details: http://www.oreilly.com/catalog/javacook2/index.html
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: ProdCons2.java,v 1.9 2004/02/09 03:34:07 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    do*****entation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by Ian F. Darwin.
 * 4. Neither the name of the author nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 
 * Java, the Duke mascot, and all variants of Sun's Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun's, and James Gosling's,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */

import java.util.*;
import java.io.*;

/** Producer-consumer in Java, Take II.
 */
public class ProdCons2 {

  /** Throughout the code, this is the object we synchronize on so this
   * is also the object we wait() and notifyAll() on.
   */
  protected LinkedList list = new LinkedList();
  protected int MAX = 10;
  protected boolean done = false// Also protected by lock on list.

  /** Inner class representing the Producer side */
  class Producer extends Thread {

    public void run() {
      while (true) {
        Object justProduced = getRequestFromNetwork();
        // Get request from the network - outside the synch section.
        // We're simulating this actually reading from a client, and it
        // might have to wait for hours if the client is having coffee.
        synchronized(list) {
            while (list.size() == MAX// queue "full"
            try {
              System.out.println("Producer WAITING");
              list.wait();   // Limit the size
            catch (InterruptedException ex) {
              System.out.println("Producer INTERRUPTED");
            }
          list.addFirst(justProduced);
          list.notifyAll();  // must own the lock
          System.out.println("Produced 1; List size now " + list.size());
          if (done)
            break;
          // yield();  // Useful for green threads & demo programs.
        }
      }
    }

    Object getRequestFromNetwork() {  // Simulation of reading from client
      // try {
      //   Thread.sleep(10); // simulate time passing during read
      // } catch (InterruptedException ex) {
      //   System.out.println("Producer Read INTERRUPTED");
      // }
      return(new Object());
    }
  }

  /** Inner class representing the Consumer side */
  class Consumer extends Thread {
    public void run() {
      while (true) {
        Object obj = null;
        synchronized(list) {
          while (list.size() == 0) {
            try {
              System.out.println("CONSUMER WAITING");
              list.wait();  // must own the lock
            catch (InterruptedException ex) {
              System.out.println("CONSUMER INTERRUPTED");
            }
          }
          obj = list.removeLast();
          list.notifyAll();
          int len = list.size();
          System.out.println("List size now " + len);
          if (done)
            break;
        }
        process(obj);  // Outside synch section (could take time)
        //yield(); DITTO
      }
    }

    void process(Object obj) {
      // Thread.sleep(xxx) // Simulate time passing
      System.out.println("Consuming object " + obj);
    }
  }

  ProdCons2(int nP, int nC) {
    for (int i=0; i<nP; i++)
      new Producer().start();
    for (int i=0; i<nC; i++)
      new Consumer().start();
  }

  public static void main(String[] args)
  throws IOException, InterruptedException {

    // Start producers and consumers
    int numProducers = 4;
    int numConsumers = 3;
    ProdCons2 pc = new ProdCons2(numProducers, numConsumers);

    // Let it run for, say, 10 seconds
    Thread.sleep(10*1000)

    // End of simulation - shut down gracefully
    synchronized(pc.list) {
      pc.done = true;
      pc.list.notifyAll();
    }
  }
}
/**
* Java Code from Java Cookbook, Second Edition
* By Ian F. Darwin
* Second Edition June 2004
* Series: Cookbooks
* ISBN: 0-596-00701-9
* Details: http://www.oreilly.com/catalog/javacook2/index.html
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/

import java.util.*;
import java.io.*;
import java.util.concurrent.*;

/** Producer-Consumer in Java, for J2SE 1.5 using concurrent.
 */
public class ProdCons15 {

  protected boolean done = false;

  /** Inner class representing the Producer side */
  class Producer implements Runnable {

    protected BlockingQueue queue;

    Producer(BlockingQueue theQueue) { this.queue = theQueue; }

    public void run() {
      try {
        while (true) {
          Object justProduced = getRequestFromNetwork();
          queue.put(justProduced);
          System.out.println("Produced 1 object; List size now " + queue.size());
          if (done) {
            return;
          }
        }
      catch (InterruptedException ex) {
        System.out.println("Producer INTERRUPTED");
      }
    }

    Object getRequestFromNetwork() {  // Simulation of reading from client
      try {
          Thread.sleep(10)// simulate time passing during read
      catch (InterruptedException ex) {
         System.out.println("Producer Read INTERRUPTED");
      }
      return(new Object());
    }
  }

  /** Inner class representing the Consumer side */
  class Consumer implements Runnable {
    protected BlockingQueue queue;

    Consumer(BlockingQueue theQueue) { this.queue = theQueue; }

    public void run() {
      try {
        while (true) {
          Object obj = queue.take();
          int len = queue.size();
          System.out.println("List size now " + len);
          process(obj);
          if (done) {
            return;
          }
        }
      catch (InterruptedException ex) {
          System.out.println("CONSUMER INTERRUPTED");
      }
    }

    void process(Object obj) {
      // Thread.sleep(xxx) // Simulate time passing
      System.out.println("Consuming object " + obj);
    }
  }

  ProdCons15(int nP, int nC) {
    BlockingQueue myQueue = new LinkedBlockingQueue();
    for (int i=0; i<nP; i++)
      new Thread(new Producer(myQueue)).start();
    for (int i=0; i<nC; i++)
      new Thread(new Consumer(myQueue)).start();
  }

  public static void main(String[] args)
  throws IOException, InterruptedException {

    // Start producers and consumers
    int numProducers = 4;
    int numConsumers = 3;
    ProdCons15 pc = new ProdCons15(numProducers, numConsumers);

    // Let the simulation run for, say, 10 seconds
    Thread.sleep(10*1000)

    // End of simulation - shut down gracefully
    pc.done = true;
  }
}
/**
* Java Code from Java Cookbook, Second Edition
* By Ian F. Darwin
* Second Edition June 2004
* Series: Cookbooks
* ISBN: 0-596-00701-9
* Details: http://www.oreilly.com/catalog/javacook2/index.html
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*/



References.

The list of classes which were used on this page you can find below. The links to Java API contain official SUN documentation about all used classes.

  java.awt.MediaTracker

  java.util.LinkedList

  java.lang.Object

  java.awt.List

  java.lang.InterruptedException

  java.io.IOException

  java.lang.Thread

  java.lang.Runnable

  java.util.concurrent.BlockingQueue

  java.util.concurrent.LinkedBlockingQueue




[ Go Back ]



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy