• Java 多线程 -- 协作模型:生产消费者实现方式二:信号灯法


    使用信号灯法实现生产消费者模式需要借助标志位。
    下面以演员表演,观众观看电视为列,写一个demo

    同一资源 电视:

    //同一资源 电视
    class Tv {
    	String voice;
    	// 信号灯
    	// T 表示演员表演 观众等待
    	// F 表示观众观看 演员等待
    	boolean flag = true;
    
    	// 表演
    	public synchronized void play(String voice) {
    		if(!flag) {
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.println("表演了:" + voice);
    		this.voice = voice;
    		// 唤醒
    		this.notifyAll();
    		// 切换标志
    		this.flag = !this.flag;
    	}
    
    	// 观看
    	public synchronized void watch() {
    		if(flag) {
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.println("听到了:" + voice);
    		
    		// 唤醒
    		this.notifyAll();
    		// 切换标志
    		this.flag = !this.flag;
    	}
    
    }
    

    生产者 演员:

    //生产者 演员
    class Player extends Thread {
    	Tv tv;
    
    	public Player(Tv tv) {
    		this.tv = tv;
    	}
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 20; i++) {
    			if (i % 2 == 0) {
    				this.tv.play("琅琊榜");
    			} else {
    				this.tv.play("太火了,插播一条广告");
    			}
    		}
    	}
    }
    

    消费者 观众:

    //消费者 观众
    class Watcher extends Thread {
    	Tv tv;
    
    	public Watcher(Tv tv) {
    		this.tv = tv;
    	}
    	
    	@Override
    	public void run() {
    		for (int i = 0; i < 20; i++) {
    			this.tv.watch();
    		}
    	}
    
    }
    

    测试代码:

    public class Cotest02 {
    	public static void main(String[] args) {
    		Tv tv = new Tv();
    		new Player(tv).start();
    		new Watcher(tv).start();
    				
    	}
    }
    

    运行结果:

    在这里插入图片描述

    代码运行正常,使用信号灯法实现生产消费者模式成功。

    重视基础,才能走的更远。
  • 相关阅读:
    C#分割字符串
    Android中this、super的区别
    Android activity跳转方式
    Android中的各种单位
    Android布局方式_RelativeLayout
    Parallelism , Partitioner
    编译hadoop,spark遇到的问题总结
    scala,spark练习题提高
    元组复杂例子
    sparksql 操作hive
  • 原文地址:https://www.cnblogs.com/xzlf/p/12681523.html
Copyright © 2020-2023  润新知