码迷,mamicode.com
首页 > 编程语言 > 详细

Java并发学习之十三——在同步代码中使用条件

时间:2014-09-15 17:47:29      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:生产者消费者

本文是学习网络上的文章时的总结,感谢大家无私的分享。

其实很简单,大家看代码就知道是神马意思了。

package chapter2;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class EventStorage {

	private int maxSize;
	private List<Date> storage;
	
	public EventStorage(){
		maxSize = 10;
		storage = new LinkedList<Date>();
	}
	
	public synchronized void set(){
		while(storage.size() == maxSize){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		((LinkedList<Date>) storage).offer(new Date());
		System.out.println("Set:"+storage.size());
		notifyAll();
	}
	
	public synchronized void get(){
		while(storage.size()==0){
			System.out.println("---------------------------等待中--------------------");
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.printf("Get:%d:%s",storage.size(),((LinkedList<Date>) storage).poll());
		notifyAll();
	}
}

package chapter2;

public class Producer implements Runnable{
	private EventStorage storage;
	public Producer(EventStorage storage){
		this.storage = storage;
	}
	@Override
	public void run() {

		for(int i=0;i<100;i++){
			storage.set();
		}
	}
}

package chapter2;

public class Consumer implements Runnable {

	private EventStorage storage;
	public Consumer(EventStorage storage){
		this.storage = storage;
	}
	@Override
	public void run() {
		for(int i=0;i<100;i++){
			storage.get();
		}
	}
}

这是对生产者和消费者问题的一种简单解决。

Java并发学习之十三——在同步代码中使用条件

标签:生产者消费者

原文地址:http://blog.csdn.net/junshuaizhang/article/details/39295113

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!