1.java.lang.IllegalMonitorStateException异常原因:
wait()/notify()/notifyAll(),应该是由监视器对象(锁对象)进行调用,而不能有其他对象调用
2.见代码中标注- class Producer implements Runnable {
- private static int pid=0;
- public Basket basektp;
- Producer(Basket basket){
- basektp = basket;
- }
-
- public synchronized void run(){
- produce();
- }
-
- public synchronized void produce(){
- while(basektp.index == basektp.capacity) {
- try{
- this.wait(); //1.修改basektp.wait();
- }catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- basektp.mtarr[basektp.index] = new Mt(++pid);
- System.out.println("produced mid:"+basektp.mtarr[basektp.index].mid);
- basektp.index++;
- this.notifyAll(); //1.修改basektp.notifyAll();
- }
- }
- class Consumer implements Runnable {
- public Basket basektc;
-
- Consumer(Basket basket){
- basektc = basket;
- }
-
- public synchronized void run(){
- consume();
- }
- public synchronized void consume(){
- while (basektc.index==0){
- try{
- this.wait(); //1.修改basektc.wait();
- }catch (InterruptedException e){
- e.printStackTrace();
- }
- }
- System.out.println("consumed mid:"+basektc.mtarr[basektc.index-1].mid); //2.basektc.index需要-1,因为Producer生产了一个馒头,放在了数组mtarr[0],而basektc.index是1,你在这边准备消费mtarr[1],而mtarr[1]是null,所以造成NullPointerException异常
- basektc.mtarr[basektc.index]=null;
- basektc.index--;
- this.notifyAll(); //1.修改basektc.notifyAll();
- }
- }
复制代码 |