java.lang.IllegalMonitorStateException
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                java.lang.IllegalMonitorStateException
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                轉載自:https://blog.csdn.net/intlgj/article/details/6245226
java.lang.IllegalMonitorStateException 
 違法的監控狀態異常。當某個線程試圖等待一個自己并不擁有的對象(O)的監控器或者通知其他線程等待該對象(O)的監控器時,拋出該異常。
例子:
//計算線程
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(); } }//獲取計算結果并輸出
package 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 異常” 
 所以我們現在就可以明確錯誤的原因了
總結
以上是生活随笔為你收集整理的java.lang.IllegalMonitorStateException的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 普通的101键盘在Mac上的键位对应
- 下一篇: oracle怎样查询某用户下的所有表的表
