java生产者消费者问题

自己的实现1

package rainbow.test;

import rainbow.test.foods;

public class ThreadTest1 {
	
	public static void main(String[] args) {
		foods foo = new foods();
		
		new pro(foo).start();
		new cons(foo).start();
	}
}

class pro extends Thread{

	foods foo = null;
	
	public pro(foods foo){
		this.foo = foo;
	}
	
	@Override
	public void run(){
		for(int i = 1; i < 11; i++){
			foo.proFood(i);
		}
	}
}

class cons extends Thread{
	
	foods foo = null;
	
	public cons(foods foo){
		this.foo = foo;
	}
	
	@Override
	public void run(){
		while(true){
			foo.conFood();
		}
	}
}


package rainbow.test;

import java.util.LinkedList;

public class foods {
	
	private LinkedList<String> foods = new LinkedList<String>();
	
	private int MAX = 10;
	
	public synchronized void conFood(){
		if(foods.size() == 0){
			System.out.println("1No Food!");
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("1Got " + foods.getFirst());
		foods.removeFirst();
		notify();
	}
	
	public synchronized void proFood(int index){
		if(foods.size() == MAX){
			System.out.println("1Full!");
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		if(foods.size() > 0){
			System.out.println("1Has food!");
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		foods.addFirst("Food " + index);
		System.out.println("1Add new Food: " + index);
		notify();
	}

}

自己的实现2

package rainbow.test;

import java.util.LinkedList;


public class ThreadTest {
	
	private byte lock[] = new byte[1];
	
	private LinkedList<String> foods = new LinkedList<String>();
	
	private int MAX = 10;

	public static void main(String[] args) {
		new ThreadTest();
	}
	
	public ThreadTest(){
		new pro().start();
		new con().start();
	}
	
	class pro extends Thread{
		
		@Override
		public void run(){
			for(int i = 1; i < 10; i++){
				synchronized(lock){
					if(foods.size() == MAX){
						System.out.println("List full!");
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					
					if(foods.size() > 0){
						System.out.println("Has food!");
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println("Add new Food: " + i);
					foods.addFirst("Food: " + i);
					lock.notify();
				}
			}
		}
	}
	
	class con extends Thread{
	
		@Override
		public void run(){
			while(true){
				synchronized(lock){
					if(foods.size() == 0){
						System.out.println("No Food!");
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					
					System.out.println("Got " + foods.getFirst());
					foods.removeFirst();
					lock.notify();
				}
			}
		}
	}
}
posted @ 2011-07-13 13:03  lostyue  阅读(258)  评论(0编辑  收藏  举报