注意:
java中的notifyAll和notify都是喚醒線程的操作,notify只會喚醒等待池中的某一個線程,但是不確定是哪一個線程,notifyAll是針對指定對象里面的所有線程執行喚醒操作,指定對象一旦喚醒成功。則會立即加入線程的資源爭奪中去。
例如:
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() + "當前沒有被執行到!" ); } } } 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(); // 針對當前對象執行喚醒所有線程的操作 System.out.println(Thread.currentThread().getName() + ":喚醒線程執行成功!" ); } } } |
執行結果為:
以上所述是小編給大家介紹的Java線程中的notifyAll喚醒操作,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/chaiyesong/archive/2017/03/24/6610110.html