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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值