生产者消费者问题。

package learn;
class applePlate{
	int apple;
	int space;
	applePlate(int apple, int space){
		this.apple = apple;
		this.space = space;
	}
	void addapple(){
		apple++;
		space--;
	}
	void eatapple(){
		space++;
		apple--;
	}
	public String toString(){
		return "apple = " + apple + ", space = " + space;
	}
}

class ProduceApple implements Runnable{
	applePlate appleplate;
	int count;
	String name;
	ProduceApple(applePlate appleplate, int count, String name){
		this.appleplate = appleplate;
		this.count = count;
		this.name = name;
	}
	public void run(){
		while(count-- > 0){
			synchronized(appleplate){
				while(appleplate.space <= 0){
					try{
						appleplate.wait();
					}catch(InterruptedException e){
						throw new RuntimeException(e);
					}
				}
				appleplate.addapple();
				System.out.println(name + " produced: " + appleplate);
				appleplate.notifyAll();
			}
		}
	}
}

class Customer implements Runnable{
	applePlate appleplate;
	int count;
	String name;
	Customer(applePlate appleplate, int count, String name){
		this.appleplate = appleplate;
		this.count = count;
		this.name = name;
	}
	public void run(){
		while(count-- > 0){
			synchronized(appleplate){
				while(appleplate.apple <= 0){
					try{
						appleplate.wait();
					}catch(InterruptedException e){
						throw new RuntimeException(e);
					}
				}
				appleplate.eatapple();
				System.out.println(name + " ate: " + appleplate);
				appleplate.notifyAll();
				
			}
		}
	}
}


class Go{
	public static void main(String args[]){
		applePlate appleplate = new applePlate(3, 2);
		System.out.println(appleplate);
		new Thread( new Customer(appleplate, 5, "c1")).start();
		new Thread( new ProduceApple(appleplate, 4, "p1")).start();
		new Thread( new Customer(appleplate, 4, "c2")).start();
		new Thread( new ProduceApple(appleplate, 3, "p2")).start();
	}
}

你可能感兴趣的:(生产者消费者)