生产者-消费者与队列

编写一段生产者/消费者的Java代码,其中生产者每次生产1个0到1000之间的随机数,消费者则把该随机数打印出来。如果产生的随机数为0,则生产者、消费者均退出运行。要求生产者、消费者均使用线程来实现

  1 package cn.yxw.test;
  2 
  3 import java.util.Random;
  4 import java.util.concurrent.ArrayBlockingQueue;
  5 import java.util.concurrent.BlockingQueue;
  6 
  7 public class ThreadTest {
  8 
  9     /**
 10      * @param args
 11      */
 12     public static void main(String[] args) {
 13         Storage storage = new Storage();
 14         new Producer(storage).start();
 15         new Customer(storage).start();
 16 
 17     }
 18 
 19 }
 20 
 21 class Customer extends Thread {
 22 
 23     private Storage storage;
 24 
 25     public Customer(Storage storage) {
 26         this.storage = storage;
 27     }
 28 
 29     public void run() {
 30         while (true) {
 31             try {
 32                 if (Storage.NUM == 0) {
 33                     System.out.println("打印:" + 0 + ",线程终止");
 34                     break;
 35                 }
 36                 Integer num = storage.print();
 37                 System.out.println("打印:" + num);
 38                 Thread.sleep(10);
 39             } catch (InterruptedException e) {
 40                 e.printStackTrace();
 41             }
 42         }
 43     }
 44 }
 45 
 46 class Producer extends Thread {
 47 
 48     private Storage storage;
 49 
 50     public Producer(Storage storage) {
 51         this.storage = storage;
 52     }
 53 
 54     public void run() {
 55 
 56         while (true) {
 57 
 58             try {
 59                 Integer num = new Random().nextInt(1000);
 60                 Storage.NUM = num;
 61                 if (Storage.NUM == 0) {
 62                     System.out.println("生产:" + 0 + ",线程终止");
 63                     break;
 64                 }
 65                 storage.put(num);
 66                 System.out.println("生产:" + num);
 67                 Thread.sleep(10);
 68             } catch (InterruptedException e) {
 69                 e.printStackTrace();
 70             }
 71 
 72         }
 73 
 74     }
 75 }
 76 
 77 class Storage {
 78     private BlockingQueue<Integer> randomData = new ArrayBlockingQueue<Integer>(
 79             1);// 空间大小为1的阻塞队列
 80 
 81     public static int NUM = -1;
 82 
 83     public void put(Integer number) {
 84 
 85         try {
 86             randomData.put(number);
 87         } catch (InterruptedException e) {
 88             e.printStackTrace();
 89         }
 90 
 91     }
 92 
 93     public int print() {
 94         try {
 95             Integer number = randomData.take();
 96             return number;
 97         } catch (InterruptedException e) {
 98             e.printStackTrace();
 99         }
100         return 0;
101     }
102 }

先保存下来,慢慢学习

posted @ 2013-10-10 15:56  一见如故  阅读(402)  评论(0编辑  收藏  举报