KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ProducerConsumer


1
2 /*
3  * Copyright © 2002 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
4  * California 95054, U.S.A. All rights reserved. Sun Microsystems, Inc. has
5  * intellectual property rights relating to technology embodied in the product
6  * that is described in this document. In particular, and without limitation,
7  * these intellectual property rights may include one or more of the U.S.
8  * patents listed at http://www.sun.com/patents and one or more additional
9  * patents or pending patent applications in the U.S. and in other countries.
10  * U.S. Government Rights - Commercial software. Government users are subject
11  * to the Sun Microsystems, Inc. standard license agreement and applicable
12  * provisions of the FAR and its supplements. Use is subject to license terms.
13  * Sun, Sun Microsystems, the Sun logo and Java are trademarks or registered
14  * trademarks of Sun Microsystems, Inc. in the U.S. and other countries. This
15  * product is covered and controlled by U.S. Export Control laws and may be
16  * subject to the export or import laws in other countries. Nuclear, missile,
17  * chemical biological weapons or nuclear maritime end uses or end users,
18  * whether direct or indirect, are strictly prohibited. Export or reexport
19  * to countries subject to U.S. embargo or to entities identified on U.S.
20  * export exclusion lists, including, but not limited to, the denied persons
21  * and specially designated nationals lists is strictly prohibited.
22  */

23
24
25 public class ProducerConsumer {
26
27   /**
28    * A single producer-consumer instance that is used by others.
29    */

30   public static ProducerConsumer pc = new ProducerConsumer();
31
32   /**
33    * The data structure where the tokens are stored.
34    */

35   private java.util.Vector JavaDoc queue = new java.util.Vector JavaDoc();
36
37   /**
38    * The producer calls this method to add a new token
39    * whenever it is available.
40    */

41   synchronized public void addToken(Token token) {
42     queue.addElement(token);
43     notify();
44   }
45
46   /**
47    * The consumer calls this method to get the next token
48    * in the queue. If the queue is empty, this method
49    * blocks until a token becomes available.
50    */

51   synchronized public Token getToken() {
52     if (queue.size() == 0) {
53       try {
54         wait();
55       } catch (InterruptedException JavaDoc willNotHappen) {
56         throw new Error JavaDoc();
57       }
58     }
59     Token retval = (Token)(queue.elementAt(0));
60     queue.removeElementAt(0);
61     return retval;
62   }
63
64 }
65
Popular Tags