IllegalMonitorStateException源代码注释说明:
Thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.
当前线程正等待一个同步监视器或者无法唤醒等待同步监视器的其他线程
1.接口的实现类中
class Number implement Runnable {
public void run(){
synchronized(this){
notify();
wait();
}
}
)
2.继承Thread类的使用(具体代码如下)
//通过继承Thread类的方法调用线程,为避免建造多个对象时共享数据的
//重复使用,将
//共享数据number设置为static,因此使用唯一类Number.class并放入
//synchronized()中,调用notify(),wait()时,显示
//IllegalMonitorStateException.
package day02_1;
/**
* 使用两个线程打印 1-100。线程1, 线程2 交替打印
* @author Xiaotong Xu
* @create 2020-12-309:40
*/
package day02_1;
/**
* 使用两个线程打印 1-100。线程1, 线程2 交替打印
* @author Xiaotong Xu
* @create 2020-12-309:40
*/
class Number extends Thread {
private static int number = 0;
private static Object obj=new Object();
@Override
public void run() {
synchronized (Number.class) {
while (true) {
Number.class.notify();
//错误方法:notify(); 直接调用notify(),默认使用 this.notify() 非此监视
//器的对象,因此出现异常
if (number <= 100) {
System.out.println(currentThread().getName() + ":" + number);
number++;
}
else {
break;
}
try {
Number.class.wait();
**//错误方法:wait(); 直接调用wait(),默认使用 this.wait() 非此监视
//器的对象,因此出现异常**
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Communication {
public static void main(String[] args) {
Number number = new Number();
Number number2 = new Number();
number.start();
number2.start();
}
}