why both wait() and notify() methods should be in synchronized blocks?

2015-05-25 06:30:01 阅读( 1 )

1952人 收藏本页


For example, one thread read data from a buffer and one thread write data into buffer. The reading data thread needs to wait until the writing data thread completely write a block data into the buffer. The writing data thread needs to wait until the reading data thread completely read the data from the buffer. If wait(), notify(), and notifyAll() methods can be called by a ordinary method , the reading thread calls wait() and the thread is being added to waiting queue . At just the same moment, the writing thread calls notify() to signal the condition changes. The reading thread misses the change and waits forever. Hence, they must be called inside a synchronized method or block which is mutually exclusive.


下一篇:初级Java程序员面试题 Junior Java programmer interview questions

上一篇:Sr. Java Developer Job Interview Questions

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题