wait()、notify()需要在同步块中使用

为什么wait()、notify()需要在同步块中使用?

源码中这样说:

     *Causes the current thread to wait until another thread invokes the

     * {@link java.lang.Object#notify()} method or the

     * {@link java.lang.Object#notifyAll()} method for this object.

     * In other words, this method behaves exactly as if it simply

     * performs the call {@code wait(0)}.

     * <p>

     *当前线程必须拥有object的锁。

     * The current thread must own this object's monitor. The thread

     * releases ownership of this monitor and waits until another thread

     * notifies threads waiting on this object's monitor to wake up

     * either through a call to the {@code notify} method or the

     * {@code notifyAll} method. The thread then waits until it can

     * re-obtain ownership of the monitor and resumes execution.

     * <p>

     * As in the one argument version, interrupts and spurious wakeups are

     * possible, and this method should always be used in a loop:

     * <pre>

     *     这个例子已经说得很明白了

     *     synchronized (obj) {

     *         while (&lt;condition does not hold&gt;)

     *             obj.wait();

     *         ... // Perform action appropriate to condition

     *     }

     * </pre>

     * This method should only be called by a thread that is the owner

     * of this object's monitor. See the {@code notify} method for a

     * description of the ways in which a thread can become the owner of

     * a monitor.

     *

     * @throws  IllegalMonitorStateException  if the current thread is not

     *               the owner of the object's monitor.

     * @throws  InterruptedException if any thread interrupted the

     *             current thread before or while the current thread

     *             was waiting for a notification.  The <i>interrupted

     *             status</i> of the current thread is cleared when

     *             this exception is thrown.

     * @see        java.lang.Object#notify()

     * @see        java.lang.Object#notifyAll()

     */

public final void wait() throws InterruptedException{

   wait(0)

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值