博客
关于我
多线程设置flag标志位实现同步
阅读量:429 次
发布时间: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/

你可能感兴趣的文章
微软面试题
查看>>
Google新玩法(转载)
查看>>
C#中Dispose和Close的区别!
查看>>
如何让服务在流量暴增的情况下保持稳定输出
查看>>
一个20年技术老兵的 2020 年度技术总结
查看>>
一例完整的websocket实现群聊demo
查看>>
SQLSERVER数据库死锁与优化杂谈
查看>>
【Net】ABP框架学习之它并不那么好用
查看>>
Git 笔记
查看>>
Harbor 批量清理历史镜像
查看>>
使用Azure Functions玩转Serverless
查看>>
.NET Core 基于Websocket的在线聊天室
查看>>
使用MySQL Shell创建MGR
查看>>
win10新版wsl2使用指南
查看>>
spring-boot 使用hibernate validation对参数进行优雅的校验
查看>>
关于我
查看>>
数据结构实验之栈四:后缀式求值
查看>>
图结构练习——最小生成树(prim算法(普里姆))
查看>>
sdut 2498【aoe 网上的关键路径】
查看>>
【PHP自定义显示系统级别的致命错误和用户级别的错误】
查看>>