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

    简单的生产者、消费者,一个数据缓冲区,一个或者多个生产者把数据放入缓冲区。一个或者多个消费者将数据从缓冲区取走。该缓冲区是一个数据共享,必须进行同步处理,如果缓冲区是满的,生产者将不能放数据,同理如果缓冲区是空的,消费者将不能取数据。

    Storage.java
    
    import java.util.Date;
    import java.util.LinkedList;
    import java.util.List;
    
    public class Storage {
    	private int maxSize;
    
    	private List<Date> storage;
    
    	public Storage() {
    		maxSize = 10;
    		storage = new LinkedList<Date>();
    
    	}
    
    	public synchronized void get() {
    		while (storage.size() == 0) {
    			try {
    				wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.printf("get : %d:  %s ", storage.size(),
    				((LinkedList<?>) storage).poll());
    
    		notifyAll();
    	}
    
    	public synchronized void put() {
    		while (storage.size() == maxSize) {
    			try {
    				wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		storage.add(new Date());
    		System.out.printf("put : %d ", storage.size());
    		notifyAll();
    	}
    }
    
    Produce.java
    
    public class Produce implements Runnable {
    
    	private Storage storage;
    
    	Produce(Storage s) {
    		this.storage = s;
    	}
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 100; i++) {
    			storage.put();
    		}
    	}
    }
    
    Consumer.java
    public class Consumer implements Runnable {
    	private Storage storage;
    
    	Consumer(Storage s) {
    		this.storage = s;
    	}
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 100; i++) {
    			storage.get();
    		}
    	}
    }
    main.java
    
    public static void main(String[] args) {
    		Storage s = new Storage();
    		Produce produce = new Produce(s);
    		Consumer consumer = new Consumer(s);
    		Thread thread1 = new Thread(produce);
    		Thread thread2 = new Thread(consumer);
    		thread1.start();
    		thread2.start();
    }
    
    
  • 相关阅读:
    常见消息引擎系统对比
    kafka(一)入门
    pycharm工具的使用
    VMware下安装Ubantu 18.04
    VMware虚拟机下Ubuntu安装VMware Tools详解
    python--or 和 and 表达式
    django使用缓存之drf-extensions
    数据结构--线性表之链表
    Redis配置主从时报错“Could not connect to Redis at 192.168.0.50:6379: Connection refused not connected>”
    Rsync+sersync(inotify)实现数据实时双向同步
  • 原文地址:https://www.cnblogs.com/tonyY/p/5007667.html
Copyright © 2011-2022 走看看