zoukankan      html  css  js  c++  java
  • 多线程设置flag标志位实现同步

    信号灯解决同步问题

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

    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();
        }
    }
    
  • 相关阅读:
    从源码解读Spring如何解决bean循环依赖
    前后端分离下用jwt做用户认证
    断点调试获取程序当前位置的运行结果
    Win10安装MySQL8压缩包版
    IDEA实用快捷键推荐
    多平台博客发布工具OpenWrite的使用
    Tomcat部署多个war包
    从储值卡(会员卡)充值业务看分布式事务的设计
    再谈 PHP 未来之路
    Swoole 实战:MySQL 查询器的实现(协程连接池版)
  • 原文地址:https://www.cnblogs.com/li33/p/12723604.html
Copyright © 2011-2022 走看看