자기 실현 소비자 생산자 실례

3770 단어
// 
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();
    }
}

좋은 웹페이지 즐겨찾기