Java并发常用方法 sleep 和 wait
生活随笔
收集整理的這篇文章主要介紹了
Java并发常用方法 sleep 和 wait
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一:sleep 和 wait
sleep()方法:
wait()方法:
sleep() vs wait()
| 同步 | 不需要在同步方法或同步塊中調(diào)用 | 只能在同步上下文中調(diào)用wait方法,否則或拋出IllegalMonitorStateException異常 |
| 作用對象 | 定義在java.lang.Thread中,作用于當(dāng)前線程 | 定義在Object類中,作用于對象本身 |
| 釋放鎖資源 | 否 | 是 |
| 喚醒條件 | 超時或者調(diào)用interrupt()方法 | 其他線程調(diào)用對象的notify()或者notifyAll()方法 |
| 方法屬性 | sleep是靜態(tài)方法 | wait是實例方法 |
二:方法簽名:
sleep()方法是Thread類的靜態(tài)方法
/*** 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* <i>interrupted status</i> of the current thread is* cleared when this exception is thrown.*/public static native void sleep(long millis) throws InterruptedException;wait()方法是Object類的成員方法
/*** 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>* 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 (<condition does not hold>)* 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);}總結(jié)
以上是生活随笔為你收集整理的Java并发常用方法 sleep 和 wait的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 苹果要叫停手机“摇一摇&rd
- 下一篇: 网易举报雀巢向其提供腾讯二手制冰机,后者