生产者—消费者模式示例

package producerAndCustomer;

import java.util.ArrayList;
import java.util.List;

public class Plate {
    private List<Object> apples = new ArrayList<Object>();
    public synchronized void putApple(Object apple){
        if(apples.size()>0){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        apples.add(apple);
        notify();
        System.out.println("放了一个苹果");
    }
    public synchronized void getApple(){
        if(apples.size()==0){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        Object apple = apples.get(0);
        apples.clear();
        notify();
        System.out.println("get了一个红苹果");
        
    }
    
}
package producerAndCustomer;

public class Add implements Runnable {
    private Plate applePlate;
    private Object apple = new Object();
    public Add(Plate applePlate){
        this.applePlate = applePlate;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i = 0 ;i<5;i++){
            applePlate.putApple(apple);
        }

    }

}
package producerAndCustomer;

public class Get implements Runnable {
    private Plate applePlate;
    public Get(Plate applePlate){
        this.applePlate = applePlate;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<5;i++){
            applePlate.getApple();
        }
    }

}
package producerAndCustomer;

public class SynchroTest {
	public static void main(String args[]){
		Plate myPlate = new Plate();
		new Thread(new Get(myPlate)).start();
		new Thread(new Add(myPlate)).start();
	}
}

  

原文地址:https://www.cnblogs.com/Keven02/p/7410381.html