生产者消费者是解决什么问题的?
- 多个线程之间的同步问题。
- 解决生产者和消费者的强耦合问题。
参考代码:
package Top;
import java.util.LinkedList;
import java.util.Random;
/**
* @Author 86180
* @Date 2020/9/7 21:50
* @Version 1.0
**/
public class ProductorConsumer {
public static void main(String[] args) {
MessageQueue messageQueue = new MessageQueue(2);
for(int i = 0; i < 3; i++){
new Thread(new Productor(messageQueue, new Message(i, "消息i")), "生产者线程"+i).start();
}
for(int i = 0; i < 1; i++){
new Thread(new Consumer(messageQueue), "消费者线程"+i).start();
}
}
}
class MessageQueue{
private int capacity;
LinkedList<Message> list;
MessageQueue(int capacity){
list = new LinkedList<>();
this.capacity = capacity;
}
public synchronized void put(Message message){
while (list.size() == capacity) {
try {
System.out.println("队列已经满,生产者等待。");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果用if来判断,要注意顺序:放在addLast前面
if(list.isEmpty())this.notifyAll();
list.addLast(message);
System.out.println(Thread.currentThread().getName()+"生产了" + message.getId());
}
public synchronized Message get(){
while(list.isEmpty()){
try {
System.out.println("队列空,生产者线程等待。");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(list.size() == capacity)this.notifyAll();//如果用if来判断,要注意顺序:放在removeFirst前面
Message message = list.removeFirst();
System.out.println(Thread.currentThread().getName()+"消费了"+ message.getId());
return message;
}
}
class Productor implements Runnable{
MessageQueue ms;
Message message;
Productor(MessageQueue messageQueue, Message message){
this.ms = messageQueue;
this.message = message;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
ms.put(message);
}
}
}
class Consumer implements Runnable{
MessageQueue ms;
Consumer(MessageQueue messageQueue){
this.ms = messageQueue;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
ms.get();
}
}
}
class Message{
private int id;
private Object value;
Message(int id, Object value){
this.id = id;
this.value = value;
}
public int getId(){
return id;
}
}
定义一个Message类,表示消息队列里面存放的消息。
定义一个MessageQueue类,含put()和get()。
定义一个生产者类Productor。
定义一个消费者类Consumer。