Sleep/Wait/Notify/NofityAll/Synchronized

1、wait的用法

/**
 * 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)}.
 * 

* 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. *

* As in the one argument version, interrupts and spurious wakeups are * possible, and this method should always be used in a loop: *

 *     synchronized (obj) {
 *         while (<condition does not hold>)
 *             obj.wait(); *         ... // Perform action appropriate to condition *     } * 
* 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 interrupted * status 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); }
  • 参考wait的注解, 当调用wait的时候必须要持有监视器锁,不然会跑出非法监视器异常

image.png
为什么wait()和notify()需要搭配synchonized关键字使用

2 sleep

/**
 * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds, subject to * the precision and accuracy of system timers and schedulers. The thread * does not lose ownership of any monitors. * * @param millis
 *         the length of time to sleep in milliseconds
 * * @throws IllegalArgumentException
 *          if the value of {@code millis} is negative
 * * @throws InterruptedException
 *          if any thread has interrupted the current thread. The * interrupted status of the current thread is
 *          cleared when this exception is thrown. 
 */
 public static native void sleep(long millis) throws InterruptedException;

你可能感兴趣的:(多线程)