01 import java.util.*;
02 import java.util.concurrent.*;
03 
04 class Producer implements Runnable {
05    private final BlockingQueue<Integer> queue;
06    Producer(BlockingQueue<Integer> q) { queue = q; }
07    public void run() {
08      try {
09        while(true) { 
10          queue.put(produce())
11        }
12      catch (InterruptedException ex) { }
13    }
14    Integer produce() { 
15      try{
16        System.out.println("Producer ...");
17        Thread.currentThread().sleep(10);
18      catch (Exception e) {
19      }
20      return new Integer((int)Math.random())
21    }
22  }
23 
24 class Consumer implements Runnable {
25     private final BlockingQueue<Integer> queue;
26     private final int i;
27     Consumer(BlockingQueue<Integer> q, int i) { 
28       queue = q; 
29       this.i = i;
30     }
31     public void run() {
32       try {
33         while(true) { 
34           consume(queue.take())
35         }
36       } catch (InterruptedException ex) { }
37       }
38    void consume(Integer x) { 
39      try{
40        System.out.println("Consumer ... "+i);
41        Thread.currentThread().sleep(10);
42      } catch (Exception e) {
43      }
44    }
45 }
46 
47 public class ProducerConsumer {
48   public static void main(String[] args) {
49     BlockingQueue<Integer> q = new LinkedBlockingQueue<Integer>();
50     Producer p = new Producer(q);
51     Consumer c1 = new Consumer(q,1);
52     Consumer c2 = new Consumer(q,2);
53     new Thread(p).start();
54     new Thread(c1).start();
55     new Thread(c2).start();
56   }
57 }
Java2html