注意:
java中的notifyAll和notify都是喚醒線程的操作,notify只會(huì)喚醒等待池中的某一個(gè)線程,但是不確定是哪一個(gè)線程,notifyAll是針對(duì)指定對(duì)象里面的所有線程執(zhí)行喚醒操作,指定對(duì)象一旦喚醒成功。則會(huì)立即加入線程的資源爭(zhēng)奪中去。
例如:
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package TestThread.ThreadSynchronized; public class TestWaitAll { public static void main(String[] args) { Test1 test1 = new Test1(); Thread t = new Thread(test1, "線程1" ); Thread t1 = new Thread(test1, "線程2" ); Thread t2 = new Thread(test1, "線程3" ); Test2 test2 = new Test2(test1, "喚醒線程" ); t.start(); t1.start(); t2.start(); try { Thread.sleep( 2000 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } test2.start(); } } class Test1 implements Runnable { public void run() { synchronized ( this ) { try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "當(dāng)前沒有被執(zhí)行到!" ); } } } class Test2 extends Thread { private Test1 test1; String name; public Test2(Test1 test1, String name) { super (name); this .name = name; this .test1 = test1; } public void run() { synchronized (test1) { test1.notifyAll(); // 針對(duì)當(dāng)前對(duì)象執(zhí)行喚醒所有線程的操作 System.out.println(Thread.currentThread().getName() + ":喚醒線程執(zhí)行成功!" ); } } } |
執(zhí)行結(jié)果為:
以上所述是小編給大家介紹的Java線程中的notifyAll喚醒操作,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/chaiyesong/archive/2017/03/24/6610110.html