自我实现消费者生产者实例

//操作对象
public
class BookCase { private String book; private boolean available = false; public synchronized String get() { while (!available) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("get<==============:"+book); available = false; notifyAll(); return book; } public synchronized void put(String newBook){ while(available){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("put==============>:"+newBook); available = true; notifyAll(); book = newBook; } }

  

//生产者
public class Producer extends Thread{ private BookCase bookCase; public Producer(BookCase bookCase){ this.bookCase = bookCase; } public void run(){ for(int i=0;i<10;i++){ String book = "Book"+i; bookCase.put(book); // try { // sleep((int)Math.random()*1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } } } }

  

//消费者
public class Consumer extends Thread{
    private BookCase bookCase;

    public Consumer(BookCase bookCase){
        this.bookCase = bookCase;
    }

    public void run(){
        for(int i=0;i<10;i++){
            String book = bookCase.get();
//          System.out.println("Consumer "+i+" get: "+book);
        }
    }

}

  

//测试类
public class ProductConsumerTest {

    public static void main(String args[]){
        BookCase b = new BookCase();
        new Producer(b).start();
        new Consumer(b).start();
    }
}