1. 程式人生 > >面試題:用 wait-notify 寫一段程式碼來解決生產者-消費者問題

面試題:用 wait-notify 寫一段程式碼來解決生產者-消費者問題

public class ProductTest {

    public static void main(String[] args)   
    {  
        Clerk clerk = new Clerk();  
        Thread producerThread = new Thread(new Producer(clerk));  
        Thread consumerThread = new Thread(new Consumer(clerk));  

        producerThread.start();  
        consumerThread.start();  
    }  
    static
class Clerk { private static final int MAX_PRODUCT = 20; private static final int MIN_PRODUCT = 0; private int PRODUCT = 0; public synchronized void addProduct() { if (this.PRODUCT >= MAX_PRODUCT) { try { wait(); System.out.println("產品已滿,請稍候再生產"
); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } this.PRODUCT++; System.out.println("生產者生產了第"+this.PRODUCT+"個產品"); notifyAll(); } public
synchronized void getProduct() { if(this.PRODUCT <= MIN_PRODUCT) { try { wait(); System.out.println("產品處於缺貨狀態"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } System.out.println("消費者消費了第" + this.PRODUCT + "個產品"); this.PRODUCT--; notifyAll(); } } static class Producer implements Runnable{ private Clerk clerk; public Producer(Clerk clerk) { this.clerk=clerk; } @Override public void run() { // TODO Auto-generated method stub System.out.println("生產者開始生產產品"); while(true) { try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } clerk.addProduct(); } } } static class Consumer implements Runnable{ private Clerk clerk; public Consumer(Clerk clerk) { this.clerk=clerk; } @Override public void run() { // TODO Auto-generated method stub System.out.println("消費者開始消費產品"); while(true) { try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } clerk.getProduct(); } } } }

這裡寫圖片描述