一、使用while方式來實現線程之間的通信
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
48
49
50
51
52
|
package com.ietree.multithread.sync; import java.util.ArrayList; import java.util.List; public class MyList { private volatile static List list = new ArrayList(); public void add() { list.add( "apple" ); } public int size() { return list.size(); } public static void main(String[] args) { final MyList list1 = new MyList(); Thread t1 = new Thread( new Runnable() { @Override public void run() { try { for ( int i = 0 ; i < 10 ; i++) { list1.add(); System.out.println( "當前線程:" + Thread.currentThread().getName() + "添加了一個元素.." ); Thread.sleep( 500 ); } } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1" ); Thread t2 = new Thread( new Runnable() { @Override public void run() { while ( true ) { if (list1.size() == 5 ) { System.out.println( "當前線程收到通知:" + Thread.currentThread().getName() + " list size = 5 線程停止.." ); throw new RuntimeException(); } } } }, "t2" ); t1.start(); t2.start(); } } |
程序輸出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. Exception in thread "t2" 當前線程收到通知:t2 list size = 5 線程停止.. java.lang.RuntimeException at com.ietree.multithread.sync.MyList$ 2 .run(MyList.java: 43 ) at java.lang.Thread.run(Unknown Source) 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. |
理解:線程Thread2不停地通過while語句檢測這個條件(list.size()==5)是否成立 ,從而實現了線程間的通信。但是這種方式會浪費CPU資源。
二、wait notfiy 方法實現多線程中線程之間的通信
使用這種方式實現線程通信需要注意:wait和notify必須配合synchronized關鍵字使用,wait方法釋放鎖,notify方法不釋放鎖。并且在這個例子中必須是Thread2先執行才可以。
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
package com.ietree.multithread.sync; import java.util.ArrayList; import java.util.List; public class ListAdd3 { private volatile static List list = new ArrayList(); public void add() { list.add( "apple" ); } public int size() { return list.size(); } public static void main(String[] args) { final ListAdd2 list2 = new ListAdd2(); // 1 實例化出來一個 lock // 當使用wait 和 notify 的時候 , 一定要配合著synchronized關鍵字去使用 final Object lock = new Object(); Thread t1 = new Thread( new Runnable() { @Override public void run() { try { synchronized (lock) { for ( int i = 0 ; i < 10 ; i++) { list2.add(); System.out.println( "當前線程:" + Thread.currentThread().getName() + "添加了一個元素.." ); Thread.sleep( 500 ); if (list2.size() == 5 ) { System.out.println( "已經發出通知.." ); //不釋放鎖,遇到size=5時還是繼續執行 lock.notify(); } } } } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1" ); Thread t2 = new Thread( new Runnable() { @Override public void run() { synchronized (lock) { if (list2.size() != 5 ) { try { //釋放鎖,讓其他線程執行 lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println( "當前線程:" + Thread.currentThread().getName() + "收到通知線程停止.." ); throw new RuntimeException(); } } }, "t2" ); t2.start(); t1.start(); } } |
程序輸出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 已經發出通知.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t2收到通知線程停止.. Exception in thread "t2" java.lang.RuntimeException at com.ietree.multithread.sync.ListAdd3$ 2 .run(ListAdd3.java: 59 ) at java.lang.Thread.run(Unknown Source) |
三、使用CountDownLatch類來實現多線程中線程之間的實時通信
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package com.ietree.multithread.sync; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; public class ListAdd2 { private volatile static List list = new ArrayList(); public void add() { list.add( "apple" ); } public int size() { return list.size(); } public static void main(String[] args) { final ListAdd2 list2 = new ListAdd2(); final CountDownLatch countDownLatch = new CountDownLatch( 1 ); Thread t1 = new Thread( new Runnable() { @Override public void run() { try { for ( int i = 0 ; i < 10 ; i++) { list2.add(); System.out.println( "當前線程:" + Thread.currentThread().getName() + "添加了一個元素.." ); Thread.sleep( 500 ); if (list2.size() == 5 ) { System.out.println( "已經發出通知.." ); countDownLatch.countDown(); } } // } } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1" ); Thread t2 = new Thread( new Runnable() { @Override public void run() { if (list2.size() != 5 ) { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println( "當前線程:" + Thread.currentThread().getName() + "收到通知線程停止.." ); throw new RuntimeException(); } }, "t2" ); t2.start(); t1.start(); } } |
程序輸出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 已經發出通知.. Exception in thread "t2" 當前線程:t1添加了一個元素.. 當前線程:t2收到通知線程停止.. java.lang.RuntimeException at com.ietree.multithread.sync.ListAdd2$ 2 .run(ListAdd2.java: 56 ) at java.lang.Thread.run(Unknown Source) 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. 當前線程:t1添加了一個元素.. |
四、使用多線程模擬一個隊列
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
package com.ietree.multithread.sync; import java.util.LinkedList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class MyQueue { // 1、定義一個盛裝元素集合 private LinkedList<Object> list = new LinkedList<Object>(); // 2、定義一個計數器 private AtomicInteger count = new AtomicInteger(); // 3、指定上限和下限 private final int minSize = 0 ; private final int maxSize; // 4、構造方法初始化大小 public MyQueue( int size) { this .maxSize = size; } // 5、初始化一個對象用于加鎖 private Object lock = new Object(); // put(anObject): 把anObject加到BlockingQueue里,如果BlockQueue沒有空間,則調用此方法的線程被阻斷,直到BlockingQueue里面有空間再繼續. public void put(Object obj) { synchronized (lock) { if (count.get() == this .maxSize) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 1、加入元素 list.add(obj); // 2、計數器累加 count.incrementAndGet(); // 3、通知(喚醒)另外一個線程 lock.notify(); System.out.println( "新加入的元素為:" + obj); } } // take: 取走BlockingQueue里排在首位的對象,若BlockingQueue為空,阻斷進入等待狀態直到BlockingQueue有新的數據被加入. public Object take() { Object ret = null ; synchronized (lock) { while (count.get() == this .minSize) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // 1、做移除元素操作 ret = list.removeFirst(); // 2、計數器作遞減操作 count.decrementAndGet(); // 3、喚醒另外一個操作 lock.notify(); } return ret; } // 獲取長度 public int getSize() { return this .count.get(); } public static void main(String[] args) { final MyQueue mq = new MyQueue( 5 ); mq.put( "a" ); mq.put( "b" ); mq.put( "c" ); mq.put( "d" ); mq.put( "e" ); System.out.println( "當前容器的長度:" + mq.getSize()); Thread t1 = new Thread( new Runnable() { @Override public void run() { mq.put( "f" ); mq.put( "g" ); } }, "t1" ); t1.start(); Thread t2 = new Thread( new Runnable() { @Override public void run() { Object o1 = mq.take(); System.out.println( "移除的元素為:" + o1); Object o2 = mq.take(); System.out.println( "移除的元素為:" + o2); } }, "t2" ); try { TimeUnit.SECONDS.sleep( 2 ); } catch (InterruptedException e) { e.printStackTrace(); } t2.start(); } } |
程序輸出:
1
2
3
4
5
6
7
8
9
10
|
新加入的元素為:a 新加入的元素為:b 新加入的元素為:c 新加入的元素為:d 新加入的元素為:e 當前容器的長度: 5 移除的元素為:a 移除的元素為:b 新加入的元素為:f 新加入的元素為:g |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://www.cnblogs.com/Dylansuns/p/6718407.html