Java - 线程 - 生产者与消费者

/**
 * 目标:厨师做好了菜,服务员才能端走,需要交替
 */
public class Main {
    public static void main(String[] args) {
        Food f = new Food();
        Producer p = new Producer(f);
        Consumer c = new Consumer(f);
        new Thread(p).start();
        new Thread(c).start();
    }
}

/**
 * 厨师:生产者
 */
class Producer implements Runnable{
    private Food food;
    public  Producer(Food food){
        this.food = food;
    }
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            if(i%2 == 0){
                food.set("韭菜炒鸡蛋","男人多吃,有益身体健康");
            }else{
                food.set("葱爆腰花","补肾气");
            }
        }
    }
}

/**
 * 服务员:消费者
 */
class Consumer implements Runnable{
    private Food food;
    public Consumer(Food food){
        this.food = food;
    }
    @Override
    public void run() {
        for (int i = 0; i <10 ; i++) {
            food.get();
        }
    }
}

/**
 * 菜实体类
 */
class Food{
    private String name;
    private String content;
    private Boolean flag = true;  //true 可以生产  false可以消费
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    //生产,set设置
    public synchronized void set(String name,String content){
        if (flag == false){
            try {
                this.wait(); //进入等待状态,让出cpu  java.lang.Object
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.setName(name);
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.setContent(content);
        System.out.println("【生产】-->" + name + ":" + content);
        flag = false;//设置可以消费
        this.notify();//唤醒某一个线程
    }
    //消费,get获取
    public synchronized void get(){
        if (flag == true){
            try {
                this.wait(); //进入等待状态,让出cpu
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("【消费】-->" + this.getName() + ":"+ this.getContent());
        flag = true;
        this.notify();//唤醒某一个线程
    }
}

 

posted @ 2016-05-04 14:18  妖精的九尾  阅读(75)  评论(0编辑  收藏  举报