歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java多線程 sleep()和wait()的區別

Java多線程 sleep()和wait()的區別

日期:2017/3/1 10:45:59   编辑:Linux編程

接觸了一些多線程的東西,還是從java入手吧。

相信看這篇文章的朋友都已經知道進程和線程的區別,也都知道了為什麼要使用多線程了。

這兩個方法主要來源是,sleep用於線程控制,而wait用於線程間的通信,與wait配套的方法還有notify和notifyAll.

區別一:

sleep是Thread類的方法,是線程用來 控制自身流程的,比如有一個要報時的線程,每一秒中打印出一個時間,那麼我就需要在print方法前面加上一個sleep讓自己每隔一秒執行一次。就像個鬧鐘一樣。

wait是Object類的方法,用來線程間的通信,這個方法會使當前擁有該對象鎖的進程等待知道其他線程調用notify方法時再醒來,不過你也可以給他指定一個時間,自動醒來。這個方法主要是用走不同線程之間的調度的。

區別二 :

關於鎖的釋放 ,在這裡假設大家已經知道了鎖的概念及其意義。調用sleep方法不會釋放鎖(自己的感覺是sleep方法本來就是和鎖沒有關系的,因為他是一個線程用於管理自己的方法,不涉及線程通信)

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.“
調用wait方法會釋放當前線程的鎖(其實線程間的通信是靠對象來管理的,所有操作一個對象的線程是這個對象通過自己的wait方法來管理的,就好像這個對象是電視機,三個人是三個線程,那麼電視機的遙控器就是這個鎖,假如現在A拿著遙控器,電視機調用wait方法,那麼A就交出自己的遙控器,由jVM虛擬機調度,遙控器該交給誰。)【我想到一個好玩的例子:如果A拿遙控器的期間,他可以用自己的sleep每隔十分鐘調一次電視台,而在他調台休息的十分鐘期間,遙控器還在他的手上~】

區別三:

使用區域

由於wait函數的特殊意義,所以他是應該放在同步語句塊中的,這樣才有意義 。

注意:兩個方法都需要拋出異常

個人見解:有sleep和wait的第二個區別,引起了我對Java線程機制的一個疑問,目前還沒有看過JDk這方面的源碼(其實看了,是木有看懂),線程的同步管理,是不是由對象在調度,如果是對象在調度,那麼JDK 1.5新引入的ReentrantLock機制就比synchronized關鍵字更值得提倡。因為他更能反映出這麼一個機制來。好多人不能理解wait和sleep的區別,我認為就是因為synchronized關鍵字的影響。當然自己還不懂JAVA的線程具體實現,留作疑問以後有時間繼續研究吧

這個小專題貌似是學長學姐們經常面面試的題目,感謝他們的經驗分享~

Copyright © Linux教程網 All Rights Reserved