zoukankan      html  css  js  c++  java
  • 死锁解决方式之一生产消费者模式之信号灯法

    package Tread;
    
    /**
     * 生产者消费者模式:信号灯法 
     * wait():等待,释放锁;
     *  notify(); 
     *  wait和notify必须和sychronized一同使用;
     *  sleep():抱着锁睡觉:
     *
     */
    public class Movie {
    	private String pic;
    	private boolean flag = true;
    
    	// 信号灯
    	// flag=T:生产生产,消费者等待,生产完成后通知消费:
    	// flag=F:消费者消费,生产者等待,消费完成后通知生产;
    	public Movie(String pic) {
    		super();
    		this.pic = pic;
    	}
    
    	public Movie() {
    
    	}
    
    	/**
    	 * 播放功能
    	 * 
    	 * @throws InterruptedException
    	 */
    	public synchronized void play(String pic) {
    		if (!flag) {
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		try {
    			Thread.sleep(500);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		this.pic = pic;
    		System.out.println("生产了" + pic);
    		this.notify();
    		this.flag = false;
    	}
    
    	/**
    	 * 收看功能
    	 */
    	public synchronized void watch() {
    		if (flag) {
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		try {
    			Thread.sleep(200);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		this.notify();
    		this.flag = true;
    		System.out.println("消费了" + pic);
    	}
    }
    package Tread;
    
    public class Player implements Runnable {
    	private Movie m;
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 20; i++) {
    			if (0 == i % 2) {
    				m.play("左青龙");
    			} else {
    				m.play("右白虎");
    			}
    		}
    
    	}
    
    	public Player(Movie movie) {
    		super();
    		this.m = movie;
    	}
    
    }
    package Tread;
    
    public class Watcher implements Runnable {
    	private Movie m;
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 20; i++) {
    			m.watch();
    
    		}
    	}
    
    	public Watcher(Movie movie) {
    		super();
    		this.m = movie;
    	}
    }
    package Tread;
    
    public class App {
    	public static void main(String[] args) {
    		Movie m = new Movie();
    		Player p = new Player(m);
    		Watcher w = new Watcher(m);
    		new Thread(p).start();
    		new Thread(w).start();
    
    	}
    }
    

      其中Movie是公共资源;

  • 相关阅读:
    2020重新出发,NOSQL,MongoDB分布式集群架构
    2020重新出发,NOSQL,MongoDB的操作和索引
    2020重新出发,NOSQL,MongoDB是什么?
    2020重新出发,NOSQL,redis高并发系统的分析和设计
    2020重新出发,NOSQL,redis互联网架构分析
    2020重新出发,NOSQL,Redis和数据库结合
    2020重新出发,NOSQL,Redis主从复制
    collections模块
    常用模块
    python面向对象的内置函数和反射
  • 原文地址:https://www.cnblogs.com/yjxs/p/9849092.html
Copyright © 2011-2022 走看看