java 生产者和消费者问题(线程)

生产者,消费者模式

package test;

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

public class Test {
    public static void main(String[] args) {
         EventStorage storage = new EventStorage();  
            Producer producer = new Producer(storage);  
            Thread thread1 = new Thread(producer); 
            Consumer consumer = new Consumer(storage);  
            Thread thread2 = new Thread(consumer); 
            thread1.start();
            thread2.start();
    }
}
/**
 * 缓冲区
 * @author Administrator
 *
 */
 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();//等待
           System.out.println("调用方法set");
} catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } storage.add(new Date()); System.out.printf("Set: %d", storage.size()); } } public synchronized void get(){ while (storage.size()==0) { try { wait();
        System.out.println("调用方法get"); }
catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } } System.out.printf("Get: %d: %s", storage.size(),((LinkedList<?>)storage).poll()); notifyAll(); } }   

/**
*生产者类
* @author Administrator
*
*/

class Producer implements Runnable{
    private EventStorage storge;
     public Producer(EventStorage storage){
         this.storge=storage;
     }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 100; i++) {
            storge.set();
        }
    }
 }
 
/**
* 消费者类
* @author Administrator
*
*/
class Consumer implements Runnable{ private EventStorage storage; public Consumer(EventStorage storage){ this.storage=storage; } @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i <100; i++) { storage.get(); } } }
原文地址:https://www.cnblogs.com/lk617-home/p/8259753.html