• 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();
    }
    
    
  • 相关阅读:
    十六.jQuery源码解析之Sizzle设计思路.htm
    关于微信浏览不能URL传参,URL中的问号被删除
    websocket 通信协议
    java_httpservice
    Socket.Io 做个标记 下来了解下
    通过netty实现服务端与客户端的长连接通讯,及心跳检测。
    NETTY 编码器介绍
    Netty4.0学习教程
    FORM表单不刷新提交POST数据
    Linux0.11学习
  • 原文地址:https://www.cnblogs.com/tonyY/p/5007667.html
Copyright © 2020-2023  润新知