java 中多線程生產者消費者問題
前言:
一般面試喜歡問些線程的問題,較基礎的問題無非就是死鎖,生產者消費者問題,線程同步等等,在前面的文章有寫過死鎖,這里就說下多生產多消費的問題了
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
114
115
116
117
|
import java.util.concurrent.locks.*; class BoundedBuffer { final Lock lock = new ReentrantLock(); //對象鎖 final Condition notFull = lock.newCondition(); //生產者監視器 final Condition notEmpty = lock.newCondition(); //消費者監視器 //資源對象 final Object[] items = new Object[ 10 ]; //putptr生產者角標,takeptr消費者角標,count計數器(容器的實際長度) int putptr, takeptr, count; public void put(Object x) throws InterruptedException { //生產者拿到鎖 lock.lock(); try { //當實際長度不滿足容器的長度 while (count == items.length) //生產者等待 notFull.await(); //把生產者產生對象加入容器 items[putptr] = x; System.out.println(Thread.currentThread().getName()+ " put-----------" +count); Thread.sleep( 1000 ); //如果容器的實際長==容器的長,生產者角標置為0 if (++putptr == items.length) putptr = 0 ; ++count; //喚醒消費者 notEmpty.signal(); } finally { //釋放鎖 lock.unlock(); } } public Object take() throws InterruptedException { lock.lock(); try { while (count == 0 ) //消費者等待 notEmpty.await(); Object x = items[takeptr]; System.out.println(Thread.currentThread().getName()+ " get-----------" +count); Thread.sleep( 1000 ); if (++takeptr == items.length) takeptr = 0 ; --count; //喚醒生產者 notFull.signal(); return x; } finally { //釋放鎖 lock.unlock(); } } } class Consu implements Runnable{ BoundedBuffer bbuf; public Consu(BoundedBuffer bbuf) { super (); this .bbuf = bbuf; } @Override public void run() { while ( true ){ try { bbuf.take() ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Produ implements Runnable{ BoundedBuffer bbuf; int i= 0 ; public Produ(BoundedBuffer bbuf) { super (); this .bbuf = bbuf; } @Override public void run() { while ( true ){ try { bbuf.put( new String( "" +i++)) ; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //主方法 class Lock1{ public static void main(String[] args) { BoundedBuffer bbuf= new BoundedBuffer(); Consu c= new Consu(bbuf); Produ p= new Produ(bbuf); Thread t1= new Thread(p); Thread t2= new Thread(c); t1.start(); t2.start(); Thread t3= new Thread(p); Thread t4= new Thread(c); t3.start(); t4.start(); } } |
這個是jdk版本1.5以上的多線程的消費者生產者問題,其中優化的地方是把synchronized關鍵字進行了步驟拆分,對對象的監視器進行了拆離,synchronized同步,隱式的建立1個監聽,而這種可以建立多種監聽,而且喚醒也優化了,之前如果是synchronized方式,notifyAll(),在只需要喚醒消費者或者只喚醒生產者的時候,這個notifyAll()將會喚醒所有的凍結的線程,造成資源浪費,而這里只喚醒對立方的線程。代碼的解釋說明,全部在源碼中,可以直接拷貝使用。
如有疑問請留言或者到本站社區交流討論,希望通過本文能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/qq_37347341/article/details/77751226