JavaSE 基础 第62节 生产者消费者模型

2016-07-02

package com.java1995;

import java.util.List;

/**
 * 生产者
 * 
 * @author Administrator
 *
 */
public class Producer extends Thread {

    private List<Integer> list;
    private int max;

    // 构造方法
    public Producer(String name, int max, List<Integer> list) {
        super(name);
        this.max = max;
        this.list = list;
    }

    public void run() {

        while (true) {

            synchronized (list) {
                while (list.size() == max) {
                    System.out.println("仓库已满");
                    try {
                        list.wait();// 线程挂起
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                // 后面的程序
                int num = (int) (Math.random() * 100);
                list.add(num);
                System.out.println(this.getName() + "生产了:" + num);
                // 生产者通知消费者有库存,可以消费
                list.notifyAll();
            }
        }
    }

}

 

package com.java1995;

import java.util.List;

/**
 * 消费者
 * 
 * @author Administrator
 *
 */
public class Consumer extends Thread {

    private List<Integer> list;
    private int max;

    public Consumer(String name, int max, List<Integer> list) {
        super(name);
        this.max = max;
        this.list = list;
    }

    public void run() {
        while (true) {
            synchronized (list) {
                while (list.isEmpty()) {
                    System.out.println("仓库空了");
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println(this.getName() + "正在消费:" + list.get(list.size() - 1));
                list.remove(list.size() - 1);
                // 消费者通知生产者,仓库已空
                list.notifyAll();
                ;
            }
        }
    }

}

 

package com.java1995;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试类
 * 
 * @author Administrator
 *
 */
public class Test {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        int max = 100;

        Producer p = new Producer("生产者", max, list);
        Consumer c = new Consumer("消费者", max, list);

        p.start();
        c.start();
    }

}

 

【参考资料】

[1] Java轻松入门经典教程【完整版】

posted @ 2016-07-02 17:46  岑亮  阅读(197)  评论(0编辑  收藏  举报