错误记录一:线程通信时抛出Exception in thread “Thread-0” java.lang.IllegalMonitorStateException异常
生活随笔
收集整理的這篇文章主要介紹了
错误记录一:线程通信时抛出Exception in thread “Thread-0” java.lang.IllegalMonitorStateException异常
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
錯誤記錄一:線程通信時拋出Exception in thread “Thread-0” java.lang.IllegalMonitorStateException異常
完整異常:
Exception in thread “Thread-0” java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.liang.Test3.Restaurant.run(Restaurant.java:64)
異常代碼
//設置線程任務:生產包子@Overridepublic void run() {//定義一個變量int count = 0;while(true){//保證線程任務只有一個在執行synchronized (bread){//對包子狀態進行判斷if(bread.flag == true){//包子鋪調用wait方法進入等待狀態try {bread.wait();} catch (InterruptedException e) {e.printStackTrace();}}//被喚醒后執行,包子鋪生產包子//交替生產兩種包子if(count %2 == 0){//生產bread.pi = "薄皮";bread.xian = "三鮮";}else {bread.pi = "冰皮";bread.xian = "牛肉大蔥餡";}}count ++;System.out.println("包子鋪正在生產"+bread.pi+bread.xian+"包子");//生產包子要三秒try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}bread.flag = true;bread.notify();System.out.println(bread.pi+bread.xian+"的包子做好了,可以開吃");}}異常出現的原因
違法的監控狀態異常。當某個線程試圖等待一個自己并不擁有的對象(O)的監控器或者通知其他線程等待該對象(O)的監控器時,拋出該異常。
object類中wait()和notify()方法使用規律
1.當前線程”在調用wait()/notify()時,必須擁有該對象的同步鎖。
2.使用時要在同步代碼塊中使用。
觀察可以知道
count ++;System.out.println("包子鋪正在生產"+bread.pi+bread.xian+"包子");//生產包子要三秒try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}bread.flag = true;bread.notify();System.out.println(bread.pi+bread.xian+"的包子做好了,可以開吃");這一部分代碼不在同步代碼塊中,**使得 bread.notify();**找不到相應的鎖對象,從而報錯。
異常修復
@Overridepublic void run() {//定義一個變量int count = 0;while(true){//保證線程任務只有一個在執行synchronized (bread){//對包子狀態進行判斷if(bread.flag == true){//包子鋪調用wait方法進入等待狀態try {bread.wait();} catch (InterruptedException e) {e.printStackTrace();}}//被喚醒后執行,包子鋪生產包子//交替生產兩種包子if(count %2 == 0){//生產bread.pi = "薄皮";bread.xian = "三鮮";}else {bread.pi = "冰皮";bread.xian = "牛肉大蔥餡";}count ++;System.out.println("包子鋪正在生產"+bread.pi+bread.xian+"包子");//生產包子要三秒try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}bread.flag = true;bread.notify();System.out.println(bread.pi+bread.xian+"的包子做好了,可以開吃");}}}運行結果
解決錯誤參考的博客:
https://blog.csdn.net/flower_vip/article/details/54913339
總結
以上是生活随笔為你收集整理的错误记录一:线程通信时抛出Exception in thread “Thread-0” java.lang.IllegalMonitorStateException异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何下载国内外专利
- 下一篇: 基于verilog的正弦波发生器