使用for循环来测试继承Thread类时,notify、wait方法的测试

使用两个线程打印 1-100 ,线程1,线程2交替打印。测试notify()和wait()

在这道题里面,使用f继承Thread的方式创建多个线程,同步方法解决线程问题,foe循环遍历时,一直报错。但是使用实现Runnable接口的方式,while循环时,就没有报错。

  各位大神求解!!!

class  Number1 extends  Thread{

    private static int num1 ;

    private Object obj = new Object();



    @Override
    public  void run() {
        show();
}

      private synchronized  void show(){

          obj.notify();

            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for ( int num1 = 1; num1 <= 100; num1++) {
                System.out.println(Thread.currentThread().getName() + ":" + num1);


                try {
                   obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
}




public class CommunicationTest1 {

    public static void main(String[] args) {

        Number1 b1 = new Number1();
        Number1 b2 = new Number1();

        b1.setName("一号");
        b2.setName("二号");

        b1.start();
        b2.start();



    }
}
xception in thread "一号" Exception in thread "二号" java.lang.IllegalMonitorStateException
	at java.lang.Object.notify(Native Method)
	at com.atguigu.java2.Number1.show(CommunicationTest1.java:26)
	at com.atguigu.java2.Number1.run(CommunicationTest1.java:21)
java.lang.IllegalMonitorStateException
	at java.lang.Object.notify(Native Method)
	at com.atguigu.java2.Number1.show(CommunicationTest1.java:26)
	at com.atguigu.java2.Number1.run(CommunicationTest1.java:21)

代码不太对,你没有拿到obj的锁,不能调用他的 notify()和wait()。synchronized拿到的锁不是obj

试试这样

synchronized (obj) {

    obj.notify()
    xxx
}

 

您好,我是问答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题。

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~