A Prototype of Producer-Consumer

发布时间:2025-08-31 21:34:09 作者:益华网络 来源:undefined 浏览量(0) 点赞(0)
摘要:1 Queue.java 1 2 3 4 5 6 7 8

1  Queue.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
package entity;
import java.util.ArrayList;
import java.util.List;
public class Queue {
private int maxLen;
private List<Integer> list = new ArrayList<Integer>();
public Queue(int maxLen) {
this.maxLen = maxLen;
}
synchronized public void push(Integer value) {
try {
while (list.size() == maxLen) {
this.wait();
}
list.add(value);
this.notifyAll();
System.out.println(Thread.currentThread().getName() +
" push=" + value + ", List=" + list.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized public Integer pop() {
Integer value = null;
try {
while (list.size() == 0) {
this.wait();
}
value = list.get(0);
list.remove(0);
this.notifyAll();
System.out.println(Thread.currentThread().getName() +
" pop=" + value + ", List=" + list.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
}

2  Producer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package thread;
import java.util.Random;
import entity.Queue;
public class Producer extends Thread {
private Queue queue;
public Producer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
Random r = new Random();
int value = r.nextInt(10) + 100;
queue.push(value);
try {
Thread.sleep(r.nextInt(3)*1000);
}catch(Exception e){}
}
}
}

3  Consumer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package thread;
import java.util.Random;
import entity.Queue;
public class Consumer extends Thread {
private Queue queue;
public Consumer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
queue.pop();
Random r = new Random();
try {
Thread.sleep(r.nextInt(3)*1000);
}catch(Exception e){}
}
}
}

4  Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package app;
import entity.Queue;
import thread.Consumer;
import thread.Producer;
public class Main {
public static void main(String[] args) throws InterruptedException{
Queue myQueue = new Queue(5); // set the max length of the queue
for (int i=0;i<6;i++) {
new Producer(myQueue).start();
new Consumer(myQueue).start();
}
}
}

5  snapshot of running

二维码

扫一扫,关注我们

声明:本文由【益华网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【益华网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。

感兴趣吗?

欢迎联系我们,我们愿意为您解答任何有关网站疑难问题!

您身边的【网站建设专家】

搜索千万次不如咨询1次

主营项目:网站建设,手机网站,响应式网站,SEO优化,小程序开发,公众号系统,软件开发等

立即咨询 15368564009
在线客服
嘿,我来帮您!