(转)一段生产者和消费者的简单多线程代码
来源:互联网 发布:office软件视频教程 编辑:程序博客网 时间:2024/05/22 08:14
一段生产者和消费者的简单多线程代码(转自老紫竹)
- package test.thread;
- public class Producer extends Thread {
- private int number;
- private Share shared;
- public Producer(Share s, int number) {
- shared = s;
- this.number = number;
- }
- public void run() {
- for (int i = 0; i < 10; i++) {
- shared.put(i);
- System.out.println("生产者" + this.number + "输出的数据为:" + i);
- try {
- sleep((int) (Math.random() * 100));
- } catch (InterruptedException e) {}
- }
- }
- public static void main(String args[]) {
- Share s = new Share();
- Producer p = new Producer(s, 1);
- Consumer c = new Consumer(s, 1);
- p.start();
- c.start();
- }
- }
- class Consumer extends Thread {
- private int number;
- private Share shared;
- public Consumer(Share s, int number) {
- shared = s;
- this.number = number;
- }
- public void run() {
- int value = 0;
- for (int i = 0; i < 10; i++) {
- value = shared.get();
- System.out.println("消费者" + this.number + "得到的数据:" + value);
- }
- }
- }
- class Share {
- private int contents;
- private boolean available = false;
- public synchronized int get() {
- while (available == false) {
- try {
- wait();
- } catch (InterruptedException e) {}
- }
- available = false;
- notifyAll();
- return contents;
- }
- public synchronized void put(int value) {
- while (available == true) {
- try {
- wait();
- } catch (InterruptedException e) {}
- }
- contents = value;
- available = true;
- notifyAll();
- }
- }
运行结果如下:
- 生产者1输出的数据为:0
- 消费者1得到的数据:0
- 生产者1输出的数据为:1
- 消费者1得到的数据:1
- 生产者1输出的数据为:2
- 消费者1得到的数据:2
- 消费者1得到的数据:3
- 生产者1输出的数据为:3
- 生产者1输出的数据为:4
- 消费者1得到的数据:4
- 生产者1输出的数据为:5
- 消费者1得到的数据:5
- 生产者1输出的数据为:6
- 消费者1得到的数据:6
- 生产者1输出的数据为:7
- 消费者1得到的数据:7
- 生产者1输出的数据为:8
- 消费者1得到的数据:8
- 生产者1输出的数据为:9
- 消费者1得到的数据:9