(转)一段生产者和消费者的简单多线程代码

来源:互联网 发布:office软件视频教程 编辑:程序博客网 时间:2024/05/22 08:14

一段生产者和消费者的简单多线程代码(转自老紫竹)

  1. package test.thread;
  2. public class Producer extends Thread {
  3.   private int number;
  4.   private Share shared;
  5.   public Producer(Share s, int number) {
  6.     shared = s;
  7.     this.number = number;
  8.   }
  9.   public void run() {
  10.     for (int i = 0; i < 10; i++) {
  11.       shared.put(i);
  12.       System.out.println("生产者" + this.number + "输出的数据为:" + i);
  13.       try {
  14.         sleep((int) (Math.random() * 100));
  15.       } catch (InterruptedException e) {}
  16.     }
  17.   }
  18.   public static void main(String args[]) {
  19.     Share s = new Share();
  20.     Producer p = new Producer(s, 1);
  21.     Consumer c = new Consumer(s, 1);
  22.     p.start();
  23.     c.start();
  24.   }
  25. }
  26. class Consumer extends Thread {
  27.   private int number;
  28.   private Share shared;
  29.   public Consumer(Share s, int number) {
  30.     shared = s;
  31.     this.number = number;
  32.   }
  33.   public void run() {
  34.     int value = 0;
  35.     for (int i = 0; i < 10; i++) {
  36.       value = shared.get();
  37.       System.out.println("消费者" + this.number + "得到的数据:" + value);
  38.     }
  39.   }
  40. }
  41. class Share {
  42.   private int contents;
  43.   private boolean available = false;
  44.   public synchronized int get() {
  45.     while (available == false) {
  46.       try {
  47.         wait();
  48.       } catch (InterruptedException e) {}
  49.     }
  50.     available = false;
  51.     notifyAll();
  52.     return contents;
  53.   }
  54.   public synchronized void put(int value) {
  55.     while (available == true) {
  56.       try {
  57.         wait();
  58.       } catch (InterruptedException e) {}
  59.     }
  60.     contents = value;
  61.     available = true;
  62.     notifyAll();
  63.   }
  64. }
运行结果如下:
  1. 生产者1输出的数据为:0
  2. 消费者1得到的数据:0
  3. 生产者1输出的数据为:1
  4. 消费者1得到的数据:1
  5. 生产者1输出的数据为:2
  6. 消费者1得到的数据:2
  7. 消费者1得到的数据:3
  8. 生产者1输出的数据为:3
  9. 生产者1输出的数据为:4
  10. 消费者1得到的数据:4
  11. 生产者1输出的数据为:5
  12. 消费者1得到的数据:5
  13. 生产者1输出的数据为:6
  14. 消费者1得到的数据:6
  15. 生产者1输出的数据为:7
  16. 消费者1得到的数据:7
  17. 生产者1输出的数据为:8
  18. 消费者1得到的数据:8
  19. 生产者1输出的数据为:9
  20. 消费者1得到的数据:9

原创粉丝点击