• 发布订阅模型


    消息队列

    生产消费
    发布订阅

    线程->发布订阅模型

    实现

    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();
    			}
    		}
    	}
    }
    
  • 相关阅读:
    HDU 1423
    POJ 3264
    POJ 3177
    CodeForces 81A
    SPOJ RATING
    ZOJ 2588
    POJ 1523
    POJ 3667
    递归
    数据结构
  • 原文地址:https://www.cnblogs.com/kungFuPander/p/11711684.html
Copyright © 2020-2023  润新知