博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java - 线程 - 生产者与消费者
阅读量:4657 次
发布时间:2019-06-09

本文共 2416 字,大约阅读时间需要 8 分钟。

/** * 目标:厨师做好了菜,服务员才能端走,需要交替 */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();//唤醒某一个线程    }}

 

转载于:https://www.cnblogs.com/xxlogin/p/5458252.html

你可能感兴趣的文章
HTML5与CSS3权威指南之CSS3学习记录
查看>>
docker安装部署
查看>>
AVL树、splay树(伸展树)和红黑树比较
查看>>
多媒体音量条显示异常跳动
查看>>
运算符及题目(2017.1.8)
查看>>
ssh自动分发密匙脚本样板
查看>>
转 小辉_Ray CORS(跨域资源共享)
查看>>
Linux安装postgresql
查看>>
MyBatis启动:MapperStatement创建
查看>>
【 全干货 】5 分钟带你看懂 Docker !
查看>>
[转]优化Flash性能
查看>>
popStar手机游戏机机对战程序
查看>>
lambda表达式树
查看>>
二次注入原理及防御
查看>>
会话记住已登录功能
查看>>
Linux内核分析——可执行程序的装载
查看>>
第一阶段冲刺3
查看>>
父类引用指向子类对象
查看>>
网页如何实现下载功能
查看>>
IT男专用表白程序
查看>>