简单的模拟了一个消息队列
Producer:生产者
Consumer:消费者
Message:消息体
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Test4 {
public static void main(String[] args) {
BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(10);
Producer producer = new Producer(blockingQueue);
//启动一个消费者
Consumer consumer = new Consumer(blockingQueue);
Thread consumerThread = new Thread(consumer);
consumerThread.start();
int n = 0;
//模拟生产者发消息
while (true){
Message message = new Message();
message.setTopic("hello("+n+")");
message.setBody("nice to meet you("+n+")");
System.out.println("发送消息:"+message.toString());
producer.send(message);
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer{
private BlockingQueue<Message> messageQueue;
private volatile Message message;
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public Producer(BlockingQueue<Message> messageQueue){
this.messageQueue = messageQueue;
}
public void send(Message message){
try {
this.messageQueue.put(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
private volatile Message message;
private String topic;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
private BlockingQueue<Message> blockingQueue;
public Consumer(BlockingQueue<Message> blockingQueue){
this.blockingQueue = blockingQueue;
}
@Override
public void run() {
while (true) {
if (!blockingQueue.isEmpty()) {
try {
System.out.println("收到消息:" + blockingQueue.take().toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Message {
private String topic;
private String body;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "{topic:" + topic + ",body:" + body + "}";
}
}