java多线程之生产者-消费者使用Object的wait()和notify()方法实现

package com.zhong.thread;

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

/**
 * 使用 wait,notify 实现生产消费者
 */
public class Stock {

    private volatile int maxnum = 10;   //最大的容量通知消费者
    private volatile int minmun = 0;    //最小的容量通知生产者
    private String name; //定义仓库中存在的内容
    private List<String> contain = new ArrayList<String>();


    public synchronized void putOne(String name) {

        while (contain.size() > maxnum) {//如果仓库中的容量大于最大容量进行线程等待
            try {
                this.wait();//线程等待 等待消费者消费
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(1000);
            this.name = name;
            contain.add(name);
            System.out.println("生产者:" + Thread.currentThread().getName() + "生产了" + name + ",消费者赶紧来消费");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.notifyAll();//唤醒所有线程
        }


    }

    public synchronized void getOne() {
        while (contain.size() <= minmun) {
            try {
                this.wait();//线程等待 等待生产者生产
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("消费者:" + Thread.currentThread().getName() + "消费了" + contain.get(0) + ",生产者赶紧生产");
        contain.remove(0);

        this.notifyAll();//唤起
    }

    public static void main(String[] args) {

        Stock s = new Stock();
        Get get = new Get(s);
        Put put = new Put(s);
        Get get1 = new Get(s);
        Put put1 = new Put(s);

        //多个生产者和消费者对缓存区进行拿放数据
        get.start();
        put.start();
        get1.start();
        put1.start();


    }
}

/**
 * 消费者
 */
class Get extends Thread {
    private Stock s;//缓冲区

    public Get(Stock s) {
        this.s = s;
    }

    @Override
    public void run() {
        while (true) {
            s.getOne();
        }
    }
}

/**
 * 生产者
 */
class Put extends Thread {
    private Stock s;//缓冲区

    public Put(Stock s) {
        this.s = s;
    }

    @Override
    public void run() {
        while (true) {
            s.putOne("mac");
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章