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

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

posted @ 2017-08-01 16:58  十月围城小童鞋  阅读(152)  评论(0)    收藏  举报