JUC--设计模式_生产者消费者

JUC–生产者消费者

  • JUC–生产者消费者

  • 博主以黑马JUC进行学习

定义

要点

  • 与前面的保护性暂停中的GuardObject 不同,不需要产生结果和消费结果的线程一一对应
  • 消费队列可以用来平衡生产和消费的线程资源
  • 生产者仅负责产生结果数据,不关心数据如何处理,而消费者专心处理结果数据
  • 消息队列是由容量限制的,满时不会再加入数据,空时不会消耗数据
  • JDK 中各种阻塞队列,采用的就是这种模式

实现

  • 消息队列
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//消息队列类,java线程之间通信
final class MessageQueue{
//消息的队列集合
private LinkedList<Message> list = new LinkedList<>();
//队列容量
private int capcity;

public MessageQueue(int capcity){
this.capcity = capcity;
}

//获取消息
public Message take(){
//检查队列是否为空
synchronized(list){
while(list.isEmpty()){
try{
list.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
//从头取消息
Message message = list.removeFirst();
list.notifyAll();
return message;
}

}
//存入消息
public void put(Message message){
synchronized(list){
//检查对象是否已满
while(list.size() == capcity){
try{
list.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
//新消息加入队列尾部
list.addLast(message);
list.notifyAll();
}
}
}

class Message{
private int id;
private Object value;

public Message(int id, Object value){
this.id = id;
this.value = value;
}

public int getId(){
return id;
}
public Object getValue(){
return value;
}
}