代码之家  ›  专栏  ›  技术社区  ›  fhucho

简单Java并发问题

  •  2
  • fhucho  · 技术社区  · 14 年前

    线程1:

    if(!conditionFullfiled) this.wait();
    

    线程2:

    if(conditionFullfiled) thread1.notify();
    

    当某些条件满足时,我想从线程2唤醒线程1。但什么时候没有问题? thread1.notify() 被称为 if(!conditionFullfiled) ***HERE*** this.wait(); ?

    4 回复  |  直到 14 年前
        1
  •  3
  •   Community Neeleshkumar S    7 年前

    obj.wait() obj.notify() ,您需要拥有要等待/通知的对象的监视器。在代码中,您可能不需要thread1.notify()。例子:

       Object someSharedObject = ...
    

    线程1:

       synchronized(someSharedObject) {
         // while NOT if for spurious wake ups.
         while(!conditionFullfiled) someSharedObject.wait();
       }
    

    线程2:

       synchronized(someSharedObject) {
         if(conditionFullfiled) someSharedObject.notify(); // this wakes thread1
       }
    

    这个 synchronized 锁定在 someSharedObject (可以) this ,这意味着两个线程永远不会发生冲突。 .wait() 释放当前保留的监视器,以便在线程1等待时不会阻止线程2。

    编辑: 我学到了一些关于虚假觉醒的知识。这个 WAIT() 必须在 while 回路- if 是不够的。 Why do threads spontaneously awake from wait()? . 感谢恩诺·石井教我。

    编辑: 澄清的 WAIT() 释放监视器。

        2
  •  3
  •   AlexR    14 年前

    这里有两个问题。

    1. 不应对线程对象本身调用wait()和notify()。更好的方法是使用特殊的锁对象,例如

      private object lock=new object(); …… WAITE();

    syncronized(lock) {
        lock.notify(); // this line will cause the wait to terminate and the first thread to continue.
    }
    

    wait() notify()

    http://download.oracle.com/javase/6/docs/api/

        3
  •  0
  •   Ovidiu Lupas    14 年前

        4
  •  0
  •   Rogach    14 年前

    new Runnable() {
        synchronized (thread1) {
            thread1.wait() 
        }
    }