java生产者消费者模式

Producter.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
/**
* 生产者
*/
public class Producter extends Thread {

private Queue<Integer> queue;
String name;
int maxSize;
int i = 0;

public Producter(String name,Queue<Integer> queue,int maxSize){
super(name);
this.name = name;
this.queue = queue;
this.maxSize = maxSize;
}

@Override
public void run() {
while (true){
synchronized (queue){
while(queue.size() == maxSize){
try{
System.out.println("Queue is full,Productr["+name+" ]thread waiting for");
//等待
queue.wait();
}catch (Exception e){
e.printStackTrace();
}
}
System.out.println("["+name+"] producting value:+"+i );
queue.offer(i++);
queue.notifyAll();

try{
Thread.sleep(new Random().nextInt(1000));
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}

Consumer.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
public class Consumer extends Thread {

private Queue<Integer> queue;
String name;
int maxSize;

public Consumer(String name,Queue<Integer> queue,int maxSize){
super(name);
this.name = name;
this.queue = queue;
this.maxSize = maxSize;
}

@Override
public void run() {
while (true){
synchronized (queue){
while (queue.isEmpty()){
try{
System.out.println("Queue is empty,Consumer ["+name+"] thread is waiting for Producer");
//如果为空,就等待
queue.wait();
}catch (Exception e){
e.printStackTrace();
}
}

int x = queue.poll();
System.out.println("["+name+" Consumer value : "+x);
queue.notifyAll();

try{
Thread.sleep(new Random().nextInt(1000));
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}

main.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String args[]){

Queue<Integer> queue = new LinkedList<>();

Thread product1 = new Producter("p-1",queue,5);
Thread product2 = new Producter("p-2",queue,5);

Thread consumer1 = new Consumer("C1",queue,5);
Thread consumer2 = new Consumer("C2",queue,5);
Thread consumer3 = new Consumer("C3",queue,5);

product1.start();
product2.start();

consumer1.start();
consumer2.start();
consumer3.start();
}
-------------本文结束感谢您的阅读-------------