生產(chǎn)者-消費(fèi)者(producer-consumer)問(wèn)題,也稱(chēng)作有界緩沖區(qū)(bounded-buffer)問(wèn)題,兩個(gè)進(jìn)程共享一個(gè)公共的固定大小的緩沖區(qū)。其中一個(gè)是生產(chǎn)者,用于將消息放入緩沖區(qū);另外一個(gè)是消費(fèi)者,用于從緩沖區(qū)中取出消息。問(wèn)題出現(xiàn)在當(dāng)緩沖區(qū)已經(jīng)滿了,而此時(shí)生產(chǎn)者還想向其中放入一個(gè)新的數(shù)據(jù)項(xiàng)的情形,其解決方法是讓生產(chǎn)者此時(shí)進(jìn)行休眠,等待消費(fèi)者從緩沖區(qū)中取走了一個(gè)或者多個(gè)數(shù)據(jù)后再去喚醒它。同樣地,當(dāng)緩沖區(qū)已經(jīng)空了,而消費(fèi)者還想去取消息,此時(shí)也可以讓消費(fèi)者進(jìn)行休眠,等待生產(chǎn)者放入一個(gè)或者多個(gè)數(shù)據(jù)時(shí)再喚醒它。
一,首先定義公共資源類(lèi),其中的變量number是保存的公共數(shù)據(jù)。
并且定義兩個(gè)方法,增加number的值和減少number的值。由于多線程的原因,必須加上synchronized關(guān)鍵字,注意while判斷的條件。
Java代碼
二,分別定義生產(chǎn)
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
|
/** * 公共資源類(lèi) */ public class PublicResource { private int number = 0 ; /** * 增加公共資源 */ public synchronized void increace() { while (number != 0 ) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } number++; System.out.println(number); notify(); } /** * 減少公共資源 */ public synchronized void decreace() { while (number == 0 ) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } number--; System.out.println(number); notify(); } } |
者線程和消費(fèi)者線程,并模擬多次生產(chǎn)和消費(fèi),即增加和減少公共資源的number值
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
|
/** * 生產(chǎn)者線程,負(fù)責(zé)生產(chǎn)公共資源 */ public class ProducerThread implements Runnable { private PublicResource resource; public ProducerThread(PublicResource resource) { this .resource = resource; } @Override public void run() { for ( int i = 0 ; i < 10 ; i++) { try { Thread.sleep(( long ) (Math.random() * 1000 )); } catch (InterruptedException e) { e.printStackTrace(); } resource.increace(); } } } /** * 消費(fèi)者線程,負(fù)責(zé)消費(fèi)公共資源 */ public class ConsumerThread implements Runnable { private PublicResource resource; public ConsumerThread(PublicResource resource) { this .resource = resource; } @Override public void run() { for ( int i = 0 ; i < 10 ; i++) { try { Thread.sleep(( long ) (Math.random() * 1000 )); } catch (InterruptedException e) { e.printStackTrace(); } resource.decreace(); } } } |
三,模擬多個(gè)生產(chǎn)者和消費(fèi)者操作公共資源的情形,結(jié)果須保證是在允許的范圍內(nèi)。
Java代碼
1
2
3
4
5
6
7
8
9
10
11
|
public class ProducerConsumerTest { public static void main(String[] args) { PublicResource resource = new PublicResource(); new Thread( new ProducerThread(resource)).start(); new Thread( new ConsumerThread(resource)).start(); new Thread( new ProducerThread(resource)).start(); new Thread( new ConsumerThread(resource)).start(); new Thread( new ProducerThread(resource)).start(); new Thread( new ConsumerThread(resource)).start(); } } |
以上所述是小編給大家介紹的Java生產(chǎn)者和消費(fèi)者例子,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!