为什么我们需要在wait()之前使用lock()?

时间:2016-06-21 16:12:12

标签: multithreading thread-safety

在多线程应用中;
为什么我们需要在wait()之前使用lock()?如果我们没有锁定()会出现什么问题?

1 个答案:

答案 0 :(得分:1)

这个问题类似于why wait() and notify() method should be called inside synchronized block,因为要进入同步块,线程首先需要锁定对象,然后才能进入块中。

wait()和notify()基本上是inter-thread communication,的两种方法所以如果一个线程想要在某个对象上等待某些条件才能继续进行,那么它可以调用wait()然后一些其他线程在满足该条件时,该线程将在同一对象上调用notify()以通知先前等待的线程。实际上这是一个非常普遍的问题。我建议你一旦浏览下面的链接,清除你的疑虑,让你的概念更清晰。

  1. http://javarevisited.blogspot.com/2011/05/wait-notify-and-notifyall-in-java.html
  2. Why must wait() always be in synchronized block