zoukankan      html  css  js  c++  java
  • 生产者消费者模式

    生产者消费者模式见上图所看到的。

    blog宗旨:用图说话。


    代码演示样例:

    package com.huan;
    
    
    public class ProduceConsumer {
    	public static void main(String[] args) {
    		Middleware middleware = new Middleware();
    		
    		new Thread(new Producer(middleware)).start();
    		
    		new Thread(new Consumer(middleware)).start();
    	}
    }
    
    class Producer implements Runnable{
    	private Middleware middleware;
    	public Producer(Middleware middleware){
    		this.middleware = middleware;
    	}
    	
    	public void produce() throws Exception{
    		while(true){
    			middleware.put();
    		}
    	}
    
    	@Override
    	public void run() {
    		try {
    			produce();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    class Consumer implements Runnable{
    	private Middleware middleware;
    	public Consumer(Middleware middleware){
    		this.middleware = middleware;
    	}
    	
    	public void consume() throws Exception{
    		while(true){
    			middleware.get();
    		}
    	}
    
    	@Override
    	public void run() {
    		try {
    			consume();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    class Middleware{
    	private static final int MAX_SIZE = 10;
    	private int[] storage = new int[MAX_SIZE];
    	private int index = 0;
    	
    	public synchronized void put() throws Exception{
    		if(index == MAX_SIZE){
    			wait();
    		}
    		storage[index] = index;
    		System.out.println("生产了:" + index);
    		index++;
    		notify();
    	}
    	
    	public synchronized void get() throws Exception{
    		if(index == 0){
    			wait();
    		}
    		index--;
    		System.out.println("消费了:" + storage[index]);
    		notify();
    	}
    }
    

    代码缺陷:当多个消费者时,或者多个生产者时,上例代码须要完好。


  • 相关阅读:
    [Sql Server 转载]
    [C#][收集整理]
    [Sql Server][原创]
    [Sql Server][原创]
    [Sql Server][原创]
    C#代码验证sql语句是否正确(只验证不执行sql)的方法
    [Sql Server][转载] 数据库表的基本信息,你真的都了解吗?
    [Sql Server][原创] 常用 Sql 查询
    LocalProxy
    通过字符串引入模块下的属性
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7372826.html
Copyright © 2011-2022 走看看