本文實(shí)例講述了java生產(chǎn)者消費(fèi)者模式。分享給大家供大家參考,具體如下:
java的生產(chǎn)者消費(fèi)者模式,有三個(gè)部分組成,一個(gè)是生產(chǎn)者,一個(gè)是消費(fèi)者,一個(gè)是緩存。
這么做有什么好處呢?
1.解耦(去依賴),如果是消費(fèi)者直接調(diào)用生產(chǎn)者,那如果生產(chǎn)者的代碼變動(dòng)了,消費(fèi)者的代碼也需要隨之變動(dòng)
2.高效,如果消費(fèi)者直接掉生產(chǎn)者,執(zhí)行時(shí)間較長的話,會(huì)阻塞,影響其他業(yè)務(wù)的進(jìn)行
3.負(fù)載均衡,如果消費(fèi)者直接調(diào)生產(chǎn)者,那生產(chǎn)者和消費(fèi)者就得在一起了,日后業(yè)務(wù)量非常大的話,要想減輕服務(wù)器的壓力,想拆分生產(chǎn)和消費(fèi),就很困難
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** * 我是生產(chǎn)者,負(fù)責(zé)生產(chǎn) */ 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
|
/** *我是消費(fèi)者,負(fù)責(zé)消費(fèi) */ 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
|
/** * *我是緩存,負(fù)責(zé)產(chǎn)品的存(生產(chǎn)后的放置)取(消費(fèi)時(shí)的獲取) */ 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生產(chǎn)" ); list.add(param); lock.notify(); lock.wait(); } } public void consumer() throws interruptedexception { synchronized (lock) { lock.wait(); system.out.println( "product消費(fèi)" ); 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(); } } |
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/zy_281870667/article/details/70853474