发布订阅模型

消息队列

生产消费
发布订阅

线程->发布订阅模型

实现

public class Box {

	private int index = 0;
	private int size = 100;  // 阈值
	private char[] chars; // 共享区
	
	public Box(int size) {
		System.out.println("盒子被创建");
		this.size = size;
		this.chars = new char[size];
	}
	
	// 生产
	public synchronized void pru(char ch) {
		while(index == size) {
			System.out.println("内存已满,停止生产资源");
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		chars[index] = ch;
		index++;
		System.out.println("建造:"+index + "->" + ch);
		this.notify();
	}
	
	// 消费
	public synchronized char con() {
		while(index == 0) {
			System.out.println("暂无可用资源");
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		index--;
		char ch = chars[index];
		System.out.println("消费:"+index + "->" + ch);
		this.notify();
		return ch;
	}
	
	public synchronized void all() {
		for(int i=0;i<chars.length;i++) {
			System.out.print(i);
		}
		System.out.println();
		//this.notify();   // 唤醒其他线程
	}
}

/**
 * 生产者
 * @author 98543
 */
public class Producer implements Runnable{

	private Box box;
	
	public Producer(Box box) {
		this.box = box;
	}
	
	@Override
	public void run() {
		for(int i=0;i<10;i++) {
			char ch = (char)(Math.random()*26+ 'A');
			box.pru(ch);
			try {
				Thread.sleep(new Random().nextInt(1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}
/**
 * 消费者
 * @author 98543
 */
public class Constumer implements Runnable{
	
	private Box box;
	
	public Constumer(Box box) {
		this.box = box;
	}
	
	@Override
	public void run() {
		for(int i=0;i<10;i++) {
			char ch = box.con();
			try {
				Thread.sleep(new Random().nextInt(100));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
posted @ 2019-10-21 09:43  kungFuPander  阅读(507)  评论(0编辑  收藏  举报