日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java.lang.IllegalMonitorStateException

發布時間:2023/12/20 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。