本文實例講述了java生產者消費者模式。分享給大家供大家參考,具體如下:
java的生產者消費者模式,有三個部分組成,一個是生產者,一個是消費者,一個是緩存。
這么做有什么好處呢?
1.解耦(去依賴),如果是消費者直接調用生產者,那如果生產者的代碼變動了,消費者的代碼也需要隨之變動
2.高效,如果消費者直接掉生產者,執行時間較長的話,會阻塞,影響其他業務的進行
3.負載均衡,如果消費者直接調生產者,那生產者和消費者就得在一起了,日后業務量非常大的話,要想減輕服務器的壓力,想拆分生產和消費,就很困難
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** * 我是生產者,負責生產 */ public class product implements runnable { private queue q; public product(queue q) { this .q = q; } @override public void run() { try { for ( int i = 0 ; i < 3 ; i++) { q.product( "test" + i); } } catch (interruptedexception e) { e.printstacktrace(); } } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** *我是消費者,負責消費 */ public class consumer implements runnable { private queue q; public consumer(queue q){ this .q = q; } @override public void run() { try { for ( int i= 0 ; i < 3 ; i++){ q.consumer(); } } catch (interruptedexception e) { e.printstacktrace(); } } } |
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
|
/** * *我是緩存,負責產品的存(生產后的放置)取(消費時的獲取) */ public class queue { private final object lock = new object(); private list<string> list = new arraylist<string>(); public void product(string param) throws interruptedexception { synchronized (lock) { system.out.println( "product生產" ); list.add(param); lock.notify(); lock.wait(); } } public void consumer() throws interruptedexception { synchronized (lock) { lock.wait(); system.out.println( "product消費" ); if (list.size() > 0 ) { list.remove(list.size() - 1 ); } lock.notify(); } } } public class testmain { public static void main(string[] args) { queue q = new queue(); product p = new product(q); consumer s = new consumer(q); thread t1 = new thread(p); thread t2 = new thread(s); t1.start(); t2.start(); } } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://blog.csdn.net/zy_281870667/article/details/70853474