我們先來(lái)看一下實(shí)例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
class threada extends thread{ public threada(string name) { super (name); } public void run() { synchronized ( this ) { system.out.println(thread.currentthread().getname()+ " call notify()" ); notify(); } } } public class waittest { public static void main(string[] args) { threada t1 = new threada( "t1" ); synchronized (t1) { try { // 啟動(dòng)“線程t1” system.out.println(thread.currentthread().getname()+ " start t1" ); t1.start(); // 主線程等待t1通過(guò)notify()喚醒。 system.out.println(thread.currentthread().getname()+ " wait()" ); t1.wait(); system.out.println(thread.currentthread().getname()+ " continue" ); } catch (interruptedexception e) { e.printstacktrace(); } } } } |
輸出結(jié)果:main start t1 -> main wait() -> t1 call notify() -> main continue
其實(shí)調(diào)用t1.start(),t1為就緒狀態(tài),只是main方法中,t1被main線程鎖住了,t1.wait()的時(shí)候,讓當(dāng)前線程等待,其實(shí)是讓main線程等待了,然后釋放了t1鎖,t1線程執(zhí)行,打印t1 call notify(),然后喚醒main線程,最后結(jié)束;
這里說(shuō)一下wait()與sleep()的區(qū)別,他們的共同點(diǎn)都是讓線程休眠,但是wait()會(huì)釋放對(duì)象同步鎖,而sleep()不會(huì);下面的代碼t1結(jié)束之后才會(huì)運(yùn)行t2;能夠證實(shí)這一點(diǎn);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public class sleeplocktest{ private static object obj = new object(); public static void main(string[] args){ threada t1 = new threada( "t1" ); threada t2 = new threada( "t2" ); t1.start(); t2.start(); } static class threada extends thread{ public threada(string name){ super (name); } public void run(){ synchronized (obj) { try { for ( int i= 0 ; i < 10 ; i++){ system.out.printf( "%s: %d\n" , this .getname(), i); // i能被4整除時(shí),休眠100毫秒 if (i% 4 == 0 ) thread.sleep( 100 ); } } catch (interruptedexception e) { e.printstacktrace(); } } } } } |