sleep方法是thread類中定義的方法,而wait方法是object類中定義的方法。
每個物件都有乙個鎖來控制同步訪問,synchronized關鍵字可以和物件的鎖互動,來實現同步方法或同步塊。
執行sleep()方法的執行緒會主動讓出cpu(然後cpu就可以去執行其他任務),在sleep指定時間後cpu再回到該執行緒繼續往下執行(注意:sleep方法只讓出了cpu,而並不會釋放同步資源鎖!!!)
wait()方法則是指當前執行緒讓自己暫時退讓出同步資源鎖,以便其他正在等待該資源的執行緒得到該資源進而執行,只有呼叫了notify()方法,之前呼叫wait()的執行緒才會解除wait狀態,可以去參與競爭同步資源鎖,進而得到執行。(注意:notify的作用相當於叫醒睡著的人,而並不會給他分配任務,就是說notify只是讓之前呼叫wait的執行緒有權利重新參與執行緒的排程);
sleep()方法可以在任何地方使用;wait()方法則只能在同步方法或同步塊中使用;
sleep方法必須人為地為其指定時間。wait方法既可以指定時間,也可以不指定時間。
sleep方法時間到,執行緒處於臨時阻塞狀態或者執行狀態。 wait方法如果沒有被設定時間,就必須要通過notify或者notifyall來喚醒。
當二者都定義在同步中時,執行緒執行到sleep,不會釋放鎖。執行緒執行到wait,會釋放鎖。
執行結果:public
class
waitandsleep catch(interruptedexception e)
system.out.println("thread1 is going on ...");
system.out.println("thread1 is being over!");}}
}private
static
class
thread2
implements
runnablecatch(interruptedexception e)
system.out.println("thread2 is going on ...");
system.out.println("thread2 is being over!");
}}
}public
static
void
main(string args) catch(interruptedexception e)
new thread(new thread2()).start();
}}
enter thread1 ...
thread1 is waiting
enter thread2 ...
thread2 notify other thread can release wait status ...
thread2 is sleeping 3 second ...
thread2 is going on ...
thread2 is being over!
thread1 is going on ...
thread1 is being over!
java中wait 和 sleep 區別
1,wait可以指定時間也可以不指定。sleep必須指定時間。2,在同步中時,對cpu的執行權和鎖的處理不同。wait 釋放執行權,釋放鎖。sleep 釋放執行權,不釋放鎖。public class test1 class mythread extends thread override publi...
Java中wait和sleep區別
super類不同 對於sleep 方法是屬於thread類,而wait 方法,則是屬於object類。是否釋放執行緒鎖 在呼叫sleep 方法的過程中,執行緒不會釋放物件鎖。而當呼叫wait 方法的時候,執行緒會放棄物件鎖,進入等待此物件的等待鎖定池,只有針對此物件呼叫notify 方法後本執行緒才...
關於JAVA中sleep和wait
腦殼疼,今天傍晚看到sleep和wait時,頭腦中的概念也的確是模糊不清,然後又是一頓搜尋,明白了不少。1.sleep 是屬於thread類,而wait是屬於object類的且必須和notify或notifyall 一起搭配使用。sleep是執行緒控制自身的流程,而wait則屬於執行緒間通訊。該執行...