发出通知方法问题

时间:2013-11-30 13:23:01

标签: java

class Thread1 extends Thread {

    int x;

    synchronized public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "=====" + x);
            x++;
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }    
}

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
在控制台上的

我能够看到它已经通知了10次但是每次通知...为什么它没有打印计数。

1 个答案:

答案 0 :(得分:1)

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

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

您正在通知,但不要退出同步部分并继续循环。因此等待线程只能在第10次notify()调用完成并且通知线程完成循环后才会唤醒。

只需补充几点注意事项:

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