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

新手上路,请多包涵

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

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
阅读 1.3k
1 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题