博客
关于我
多线程设置flag标志位实现同步
阅读量:434 次
发布时间:2019-03-06

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

信号灯解决同步问题

我尽量注释了代码,可以很容易理解了。

package Thread;/** * 信号灯 * 借助标志位 */public class FlagThread {    public static void main(String[] args) {        Bread bread=new Bread();        new Producer(bread).start();        new Consume(bread).start();    }}class Consume extends Thread{    Bread bread;    public Consume(Bread bread) {        super();        this.bread = bread;    }    @Override    public void run() {        for(int i=1;i<100;++i) {            bread.consume();        }    }}class Producer extends Thread{    Bread bread;    public Producer(Bread bread) {        super();        this.bread = bread;    }    @Override    public void run() {        for(int i=1;i<100;++i) {            bread.produce();        }    }}//资源//同步方法要放在资源里,没有交点不会相互唤醒class Bread{    //为T表示面包在生产,为F表示可以消费了    boolean flag;//标志位,定义在需要被操控的类里面    public Bread() {//构造方法初始化flag=true        flag=true;    }    public synchronized void produce(){//同步方法用来操控生产        if(!this.flag) {//如果标志位为false,生产者等待            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }//如果标志位为true,那就生产,生产之后吧flag设置为false        System.out.println(Thread.currentThread ().getName ()+"正在生产······");//这是这句话的临界资源        this.flag=!this.flag;        this.notifyAll();    }    public synchronized void consume(){        if(this.flag) {//如果flag为真,说明没有面包,需要等待            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }//否则等待        System.out.println(Thread.currentThread ().getName ()+"正在消费·····");        this.flag=!this.flag;        this.notifyAll();    }}

转载地址:http://cenyz.baihongyu.com/

你可能感兴趣的文章
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
Node+Express连接mysql实现增删改查
查看>>
node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
查看>>
Node-RED中Button按钮组件和TextInput文字输入组件的使用
查看>>
vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
查看>>
Node-RED中Switch开关和Dropdown选择组件的使用
查看>>
Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用json节点解析JSON数据
查看>>
Node-RED中使用node-random节点来实现随机数在折线图中显示
查看>>
Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
查看>>
Node-RED中使用node-red-contrib-image-output节点实现图片预览
查看>>
Node-RED中使用node-red-node-ui-iframe节点实现内嵌iframe访问其他网站的效果
查看>>
Node-RED中使用Notification元件显示警告讯息框(温度过高提示)
查看>>
Node-RED中使用range范围节点实现从一个范围对应至另一个范围
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
Node-RED中将CSV数据写入txt文件并从文件中读取解析数据
查看>>