一个线程间通信的例题 用对象锁正常 而用类锁报错的原因?

如题 实在想不通 求大佬们解答

public class ThreadTalk {

public static void main(String[] args) {

//场景:一台可以多线程(实现了run)的打印机被两个线程操作

Printer_1 printer = new Printer_1();

Thread t1 = new Thread(printer);

Thread t2 = new Thread(printer);

t1.setName("线程一");

t2.setName("线程二");

t1.start();

t2.start();

}

}

class Printer_1 implements Runnable{

private int number = 0;

@Override

public void run() {

while (true) {

synchronized (Printer_1.class) {//使用对象锁能正常运行

notify();

if (number <= 100) {

System.out.println(Thread.currentThread().getName() + "打印数字:" + number);

number++;

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

} else {

break;

}

}

}

}

}

报错内容

Exception in thread "线程一" Exception in thread "线程二" java.lang.IllegalMonitorStateException

at java.lang.Object.notify(Native Method)

at Test2.Printer_1.run(ThreadTalk.java:26)

at java.lang.Thread.run(Thread.java:748)

java.lang.IllegalMonitorStateException

at java.lang.Object.notify(Native Method)

at Test2.Printer_1.run(ThreadTalk.java:26)

at java.lang.Thread.run(Thread.java:748)

进程已结束,退出代码0


回答:

synchronized(Printer_1.class)这样写表示将这个class对象作为锁,而你里面又是用实例对象的wait()和notify()方法,这样是不行的。你应该用Printer_1.class.wait()和Printer_1.class.notify()

以上是 一个线程间通信的例题 用对象锁正常 而用类锁报错的原因? 的全部内容, 来源链接: utcz.com/p/945000.html

回到顶部