Java 通知方法的问题

Java 通知方法的问题,java,Java,在控制台上,我可以看到它已经通知了10次,但每次通知。。。为什么它没有打印计数。notify()不会释放锁。等待线程只能在通知线程退出同步部分时唤醒。但事实并非如此: Vishesh=====0 notified..... notified..... notified..... notified..... notified..... notified..... notified..... notified..... notified..... notified..... Hi mainend o

在控制台上,我可以看到它已经通知了10次,但每次通知。。。为什么它没有打印计数。

notify()
不会释放锁。等待线程只能在通知线程退出同步部分时唤醒。但事实并非如此:

Vishesh=====0
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
Hi
mainend of main
Vishesh=====1
synchronized(thrd){
对于(int i=0;i<10;i++){
System.out.println(“已通知…”);
thrd.notify();
}
}
您正在通知,但不要离开同步部分并继续循环。因此,等待的线程只有在第10次notify()调用完成并且通知线程完成循环后才能唤醒

只需补充几点注意事项:

  • Thread1类不应扩展Thread,而应实现Runnable
  • 最好在线程之间使用共享锁,而不是将runnable本身用作锁

谢谢你的帮助,但我还有一个疑问。。如果我将代码更改为--synchronized(thrd){for(inti=0;I<10;I++){System.out.println(“notified…”);thrd.notify();thrd.wait(8);}},它工作正常,输出将是。。为什么。。Vishesh=====0已通知。。。。。Vishesh=====1已通知。。。。。Vishesh=====2已通知。。。。。Vishesh=====3已通知。。。。。Vishesh=====4已通知。。。。。Vishesh=====5通知。。。。。Vishesh=====6已通知。。。。。Vishesh=====7已通知。。。。。Vishesh=====8已通知。。。。。Vishesh=====9已通知。。。。。main的末尾读取javadoc。wait()释放锁。
public class Wait {

    public static void main(String[] args) throws InterruptedException {
        Thread1 thrd = new Thread1();
        Thread b = new Thread(thrd);
        b.setName("Vishesh");
        b.start();
        Thread.sleep(9000);
        synchronized (thrd) {

            for (int i = 0; i < 10; i++) {
                System.out.println("notified.....");
                thrd.notify();

            }

        }

        System.out.println("end of main");
    }    
}
Vishesh=====0
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
notified.....
Hi
mainend of main
Vishesh=====1
synchronized (thrd) {
    for (int i = 0; i < 10; i++) {
        System.out.println("notified.....");
        thrd.notify();
    }
}