码迷,mamicode.com
首页 > 其他好文 > 详细

死锁解决方式之一生产消费者模式之信号灯法

时间:2018-10-25 14:19:01      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:todo   package   方式   i++   ring   bool   之一   tar   row   

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是公共资源;

死锁解决方式之一生产消费者模式之信号灯法

标签:todo   package   方式   i++   ring   bool   之一   tar   row   

原文地址:https://www.cnblogs.com/yjxs/p/9849092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!