Java併發學習之十三——在同步代碼中使用條件

本文是學習網絡上的文章時的總結,感謝大家無私的分享。

其實很簡單,大家看代碼就知道是神馬意思了。

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

這是對生產者和消費者問題的一種簡單解決。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章