java.lang.IllegalMonitorStateException 如何解决问题

来源:互联网 发布:网络诈骗类型有哪些 编辑:程序博客网 时间:2024/06/04 23:28
文章应用部分摘自 http://blog.csdn.net/intlgj/article/details/6245226,大概阐述一下java.lang.IllegalMonitorStateException 违法的监控状态异常。当某个线程试图等待一个自己并不拥有的对象(O)的监控器或者通知其他线程等待该对象(O)的监控器时,抛出该异常。例子://计算线程[java] view plaincopypackage com.intlgj.thread; //计算线程 public class Calculator extends Thread { int total; public void run() { synchronized (this) { for (int i = 0; i < 10; i++) { total += i; } } // 通知所有在此对象上等待的线程 notifyAll(); } } //获取计算结果并输出[java] view plaincopypackage com.intlgj.thread; //获取计算结果并输出 public class ReaderResult extends Thread { Calculator c; public ReaderResult(Calculator c) { this.c = c; } public void run() { synchronized (c) { try { System.out.println(Thread.currentThread() + "等待计算结果。。。"); c.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread() + "计算结果为:" + c.total); } } public static void main(String[] args) { Calculator calculator = new Calculator(); // 启动10个线程,分别获取计算结果 for(int i=0;i<5;i++){ new ReaderResult(calculator).start(); } // 启动计算线程 calculator.start(); } } 运行结果 Thread[Thread-1,5,main]等待计算结果。。。Thread[Thread-2,5,main]等待计算结果。。。Thread[Thread-3,5,main]等待计算结果。。。Thread[Thread-4,5,main]等待计算结果。。。Thread[Thread-5,5,main]等待计算结果。。。Thread[Thread-5,5,main]计算结果为:45Thread[Thread-4,5,main]计算结果为:45Thread[Thread-3,5,main]计算结果为:45Thread[Thread-2,5,main]计算结果为:45Thread[Thread-1,5,main]计算结果为:45Exception in thread "Thread-0" java.lang.IllegalMonitorStateExceptionat java.lang.Object.notifyAll(Native Method)at com.intlgj.thread.Calculator.run(Calculator.java:15) 根据SCJP所要求的线程交互知识点需要从java.lang.Object的类的三个方法和以上的说法: void notify() 唤醒在此对象监视器上等待的单个线程。 void notifyAll() 唤醒在此对象监视器上等待的所有线程。 void wait() 导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。该方法只能在同步方法或同步块内部调用。如果当前线程不是对象所得持有者,该方法抛出一个java.lang.IllegalMonitorStateException 异常”所以我们现在就可以明确错误的原因了修改方法:package com.intlgj.thread; //计算线程 public class Calculator extends Thread { int total; public void run() { synchronized (this) { for (int i = 0; i < 10; i++) { total += i; } // 通知所有在此对象上等待的线程 notifyAll(); //放到synchronize同步块里面就行了 } } }
0 0