为什么会报Exception in thread "Thread-1" java.lang.IllegalMonitorStateException错误呢
来源:5-3 自由编程
应该怎么爱
2021-09-16 14:51:58
代码如下:
Weather类
public class Weather {
private double temptrue;
private double hideity;
public boolean b = true;
public double getTemptrue() {
return temptrue;
}
public void setTemptrue(double temptrue) {
this.temptrue = temptrue;
}
public double getHideity() {
return hideity;
}
public void setHideity(double hideity) {
this.hideity = hideity;
}
public void generate(){
if (!b){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setTemptrue(Math.random());
this.setHideity(Math.random());
System.out.println("生成天气:"+this.toString());
b=false;
notifyAll();
}
public void read(){
if (b){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("读取天气" + this.toString());
b=true;
notifyAll();
}
@Override
public String toString() {
return "天气{" +
"温度=" + temptrue +
", 湿度=" + hideity +
'}';
}
}
GenerateWeather类
public class GenerateWeather implements Runnable{
Weather weather;
GenerateWeather(Weather weather){
this.weather = weather;
}
@Override
public void run() {
while (true){
weather.generate();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
ReadWeather类
public class ReadWeather implements Runnable{
Weather weather;
ReadWeather(Weather weather){
this.weather = weather;
}
@Override
public void run() {
while (true){
weather.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
public class WeatherTest {
public static void main(String[] args) {
Weather weather = new Weather();
new Thread(new GenerateWeather(weather)).start();
new Thread(new ReadWeather(weather)).start();
}
}
运行报错如下:
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
生成天气:天气{温度=0.31717090087249256, 湿度=0.39180791972688567}
at com.testWeather.Weather.read(Weather.java:45)
at com.testWeather.ReadWeather.run(ReadWeather.java:12)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at com.testWeather.Weather.generate(Weather.java:36)
at com.testWeather.GenerateWeather.run(GenerateWeather.java:14)
at java.lang.Thread.run(Thread.java:745)
1回答
好帮手慕小蓝
2021-09-16
同学你好,wait()、notifyAll()、notify()三个方法需要使用在同步代码块中,否则就会出现java.lang.IllegalMonitorStateException。
出错的位置在Weather类的generate()方法和read(),如下图所示:
使用synchronized关键字对这两方法进行修饰即可,修改方式和运行结果如下图所示:
祝学习愉快~
相似问题