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

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

猜你喜欢

转载自www.cnblogs.com/yjxs/p/9849092.html