java多執行緒三 wait sleep join yield
阿新 • • 發佈:2018-11-19
一,wait
是object類的方法,並不是執行緒的方法,使用此方法會使當前執行緒進入阻塞狀態,過程中執行緒會釋放cpu資源和鎖資源,獻策韓國你進入等待池,可以通過notify或者notifyall將執行緒喚醒,是執行緒重新進入就緒狀態,在wait,notify和notifyall方法使用過程中一定要注意在同步方法或同步程式碼塊中使用,因為在同步中才會獲得鎖,才能釋放鎖,java API強制規定,否則將報出java.lang.IllegalMonitorStateException異常。
二,sleep
sleep使Thread的方法,使強制使執行緒進入睡眠狀態Thread.sleep(time)。在此過程中該執行緒只會釋放掉cpu資源並不會釋放鎖資源,也就意味著目前物件例項的搶佔到剛釋放的cpu資源的執行緒不能獲得同步資源鎖,但是可以去搶佔沒有被佔用的同步資源鎖。
三,join
join方法的原始碼
/** * Waits for this thread to die. * * <p> An invocation of this method behaves in exactly the same * way as the invocation * * <blockquote> * {@linkplain #join(long) join}{@code (0)} * </blockquote> * * @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 final void join() throws InterruptedException { join(0); //join()等同於join(0) } /** * Waits at most {@code millis} milliseconds for this thread to * die. A timeout of {@code 0} means to wait forever. * * <p> This implementation uses a loop of {@code this.wait} calls * conditioned on {@code this.isAlive}. As a thread terminates the * {@code this.notifyAll} method is invoked. It is recommended that * applications not use {@code wait}, {@code notify}, or * {@code notifyAll} on {@code Thread} instances. * * @param millis * the time to wait 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 final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); //join(0)等同於wait(0),即wait無限時間直到被notify } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }
可以看出join是一個同步方法,當主執行緒呼叫t的jion方法時會像去獲得t的鎖,然後主執行緒呼叫wait方法進入等待池,直到t執行緒執行結束main執行緒才能繼續執行。
四,yield
執行緒讓步,是將該執行緒,讓出cpu資源進入可執行狀態,然後與同優先順序的執行緒再一併競爭搶佔資源,也就是說並不意味著該執行緒一定會處於可執行狀態,當其再一次搶到資源,會立即又轉變成執行狀態。