一輩子產與多消費:操做棧

步驟同一輩子產與一消費,區別在於測試類代碼以下:java

public class Test {
    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        Produce produce = new Produce(myStack);
        Consumer consumer1 = new Consumer(myStack);
        Consumer consumer2 = new Consumer(myStack);
        Consumer consumer3 = new Consumer(myStack);
        Consumer consumer4 = new Consumer(myStack);
        Consumer consumer5 = new Consumer(myStack);
        ThreadProduce threadProduce = new ThreadProduce(produce);
        ThreadConsumer threadConsumer1 = new ThreadConsumer(consumer1);
        ThreadConsumer threadConsumer2 = new ThreadConsumer(consumer2);
        ThreadConsumer threadConsumer3 = new ThreadConsumer(consumer3);
        ThreadConsumer threadConsumer4 = new ThreadConsumer(consumer4);
        ThreadConsumer threadConsumer5 = new ThreadConsumer(consumer5);
        threadProduce.start();
        threadConsumer1.start();
        threadConsumer2.start();
        threadConsumer3.start();
        threadConsumer4.start();
        threadConsumer5.start();
    }
}

注意:運行代碼會出現數組越界異常數組

處理方法:將MyStack的push方法和pop方法中的「if」條件修改成「while」測試

再次運行代碼spa

注意:運行代碼後出現「假死」狀況code

處理方法:將MyStack的push方法和pop方法中的notify()方法修改成notifyAll()方法class

相關文章
相關標籤/搜索