多线程经典——生产者和消费者问题

来源:互联网 发布:淘宝美工全攻略百度云 编辑:程序博客网 时间:2024/05/10 12:09

说明:增加标志位,如果标志位的内容为true,则表示可以生产,但不能取走,此时线程执行到了消费者线程则应该等待;如果标志位的内容为false,则表示可以取走,但是不能生产,如果生产者线程运行,则消费者线程应该等待。

public class Product {    private String name="蒙牛";    private String content="优酸乳";    private boolean flag=false;    public synchronized void set(String name,String content){        if(!flag){         //标志位为false,不可用生产            try {                super.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        this.setName(name);        this.setContent(content);        flag=false;        super.notify();    }    public synchronized void get(){        if(flag){           //标志位为true,不可用取走            try {                super.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        System.out.println(this.getName()+"-->"+this.getContent);        flag=true;        super.notify();    }}
0 0
原创粉丝点击