生产者消费者模式(专为多线程并发设计的模式)

第一个类代码(模板)

package ProduceConsumers;

/**
 * 1 一个共同的场景,同一份资源
 * 
 * 2 生产者消费者模式  信号灯法
 *   wait()等待,会释放资源锁,而sleep()不会释放资源锁
 *   notify()或notifyAll()会唤醒线程
 * 
 * 3 此设计模式是跟synchronized一起使用的,这个模式的创建也是为了解决同步死锁的问题
 * 
 * 4 如果不添加本设计模式,直接运行两个方法虽然保证了生产和消费间歇操作,但是会出现null结果
 * @author Chyjrily
 *
 */
public class Movie {

	private String pic;
	
	//信号灯
	//flag --> true    生产者生产,消费者等待,生产完成后通知消费
	//flag --> false   消费者消费,生产者等待,消费完成后通知生产
	private boolean flag = true;
	
	//上演
	public synchronized void play(String pic) throws InterruptedException {
		if(!flag) {
			this.wait(); //生产者等待
		}
		
		Thread.sleep(5000000); //这里的模拟生产的时间为什么没用
		
		//生产完成
		this.pic = pic;
		
		//通知消费者
		this.notifyAll();
		
		//生产者停下
		this.flag = false;
		
	}
	
	//观看
	public synchronized void watch() throws InterruptedException {
		
		if(flag) {
			this.wait(); //消费者等待
		}
		
		//开始消费
		Thread.sleep(2000000); //同上
		
		//消费完成
		System.out.println(pic); 
		
		//通知生产
		this.notify();
		
		//消费停止
		this.flag = true;
		
		
	}
}

第二个类的代码(生产者)

package ProduceConsumers;

public class Player implements Runnable{

	private Movie m;
	
	public Player(Movie m) {
		super();
		this.m = m;
	}

	public void run() {
		for(int i=0; i<50; i++) {
			if(0 == i%2) {
				System.out.println("评论支持了一下崔永元");
			}else {
				System.out.println("评论损了一下冯小刚");
			}
		}
	}
}

第三个类代码(消费者)

package ProduceConsumers;

/**
 * 消费者
 * @author Chyjrily
 *
 */
public class Watcher implements Runnable{

	private Movie m;
	
	public Watcher(Movie m) {
		super();
		this.m = m;
	}

	public void run() {
	
		for(int i=0; i<50; i++) {
			try {
				m.watch();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

第四个类(运行)

package ProduceConsumers;

public class MovieApp {

	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();  //如果不加入任何同步,运行的结果会出现null,不知为何且最后一段运行结果全是null
	
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/81091348