调用wait()方法后释放锁?

时间:2018-05-11 07:07:44

标签: java multithreading thread-safety

我正在阅读关于等待并在Java中通知。

我将用一个小例子来解释:

Negative matches:

MyBeans#beanA:
      Did not match:
         - @ConditionalOnProperty (bean.a) found different value in property 'bean.a' (OnPropertyCondition)

   MyBeans#beanB:
      Did not match:
         - @ConditionalOnBean (types: org.gotson.transitivebeandependencies.BeanA; SearchStrategy: all) did not find any beans (OnBeanCondition)
      Matched:
         - @ConditionalOnProperty (bean.b) matched (OnPropertyCondition)

   MyBeans#beanC:
      Did not match:
         - @ConditionalOnBean (types: org.gotson.transitivebeandependencies.BeanB; SearchStrategy: all) did not find any beans (OnBeanCondition)
      Matched:
         - @ConditionalOnProperty (bean.c) matched (OnPropertyCondition)

这里说我们做@Override public void run() { synchronized (msg) { try{ msg.wait(); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(name+" processed: "+msg.getMsg()); } } 时。当前线程T1将锁定msg对象。

因此可以通过两种方式释放锁定:

  1. 同步块完成后
  2. 当T1 ??
  3. 调用wait()时

    如果另一个线程调用notify()并唤醒线程T1,T1将再次获得锁定synchronized (msg)对象的权限?

1 个答案:

答案 0 :(得分:2)

是的,T1将在wait时释放锁定,并且在收到通知后必须重新获取锁定。请参阅java language specification中的详细信息。

并且wait方法should可以在while循环中调用。

 synchronized (obj) {
     while (<condition does not hold>)
         obj.wait();
     ... // Perform action appropriate to condition
 }
相关问题