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();
    }
    
    
  • 相关阅读:
    asp.net 汉字转拼音类
    NET分页实现及代码
    Web.config配置文件详解(新手必看) (转载)
    偶开通博客啦
    转帖不会乱码的,powershell网络蜘蛛
    ConvertFrom-String 命令研究
    powershell玩转xml之20问
    powershell 判断操作系统版本 命令
    powershell加win的dns服务器,解决网站负载均衡问题
    PowerShell并发控制-命令行参数之四问
  • 原文地址:https://www.cnblogs.com/tonyY/p/5007667.html
Copyright © 2011-2022 走看看