接觸了一些多線程的東西,還是從java入手吧。
相信看這篇文章的朋友都已經(jīng)知道進(jìn)程和線程的區(qū)別,也都知道了為什么要使用多線程了。
這兩個方法主要來源是,sleep用于線程控制,而wait用于線程間的通信,與wait配套的方法還有notify和notifyAll.
區(qū)別一:
sleep是Thread類的方法,是線程用來 控制自身流程的,比如有一個要報(bào)時的線程,每一秒中打印出一個時間,那么我就需要在print方法前面加上一個sleep讓自己每隔一秒執(zhí)行一次。就像個鬧鐘一樣。
wait是Object類的方法,用來線程間的通信,這個方法會使當(dāng)前擁有該對象鎖的進(jìn)程等待知道其他線程調(diào)用notify方法時再醒來,不過你也可以給他指定一個時間,自動醒來。這個方法主要是用走不同線程之間的調(diào)度的。
區(qū)別二 :
關(guān)于鎖的釋放 ,在這里假設(shè)大家已經(jīng)知道了鎖的概念及其意義。調(diào)用sleep方法不會釋放鎖(自己的感覺是sleep方法本來就是和鎖沒有關(guān)系的,因?yàn)樗且粋€線程用于管理自己的方法,不涉及線程通信)
JDK 7 中的解釋:
“public static void sleep(long millis)
throws InterruptedException
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.
public final void wait() throws InterruptedException
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call 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 notify method the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.“
調(diào)用wait方法會釋放當(dāng)前線程的鎖(其實(shí)線程間的通信是靠對象來管理的,所有操作一個對象的線程是這個對象通過自己的wait方法來管理的,就好像這個對象是電視機(jī),三個人是三個線程,那么電視機(jī)的遙控器就是這個鎖,假如現(xiàn)在A拿著遙控器,電視機(jī)調(diào)用wait方法,那么A就交出自己的遙控器,由jVM虛擬機(jī)調(diào)度,遙控器該交給誰。)【我想到一個好玩的例子:如果A拿遙控器的期間,他可以用自己的sleep每隔十分鐘調(diào)一次電視臺,而在他調(diào)臺休息的十分鐘期間,遙控器還在他的手上~】
區(qū)別三:
使用區(qū)域
由于wait函數(shù)的特殊意義,所以他是應(yīng)該放在同步語句塊中的,這樣才有意義 。
注意:兩個方法都需要拋出異常