生产者与消费者问题(java实现)

package tread;

/*生产者与消费者应用案例
* 1.sleep和wait的区别
* 2.
* */

public class ThreadDemo {
    public static void main(String[] args) {
        MidChannel m = new MidChannel();
        Producter p = new Producter(m);
        Consumer c = new Consumer(m);
        new Thread(p).start();
        new Thread(c).start();
    }
}
/*生产者*/
class Producter implements Runnable{
    private MidChannel m;
    public Producter(MidChannel m){
        this.m = m;
    }
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i%2==0){
                m.set("韭菜炒鸡蛋", "男人的好食品,多吃有益身体健康");
            }else{
                m.set("从爆腰花","补肾气,通膀胱,我好她就好!");
            }
        }
    }
}
/*消费者*/
class Consumer implements Runnable{
    private MidChannel m;
    public Consumer(MidChannel m){
        this.m = m;
    }
    public void run() {
        for (int i = 0; i < 100; i++) {
            m.get();
        }
    }
}
/*中间对象*/
class MidChannel{
    private String name;
    private String describe;
    private boolean flag = true;
   
    //生产产品
    public synchronized void set(String name,String describe){
        if(!flag){
            try {
                this.wait();  //当前线程进入等待状态
                                //需要其他线程唤醒
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.setName(name);
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.setDescribe(describe);
        this.flag = false;  //表示可以消费
        this.notify(); //唤醒一个线程
    }
    //消费方法
    public synchronized void get() {
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(this.getName()!=null){
            System.out.println(this.getName()+","+this.getDescribe());
        }
        this.flag = true;
        this.notify();
    }
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescribe() {
        return describe;
    }
    public void setDescribe(String describe) {
        this.describe = describe;
    }
}

你可能感兴趣的:(生产者与消费者问题(java实现))