目錄
簡介
步驟 1: 定義消息類
步驟 2: 創建發布者
步驟 3: 創建訂閱者
步驟 4: 實現發布-訂閱模型
前言-與正文無關
????????生活遠不止眼前的苦勞與奔波,它還充滿了無數值得我們去體驗和珍惜的美好事物。在這個快節奏的世界中,我們往往容易陷入工作的漩渦,忘記了停下腳步,感受周圍的世界。讓我們一起提醒自己,要適時放慢腳步,欣賞生活中的每一道風景,享受與家人朋友的溫馨時光,發現那些平凡日子里隱藏的幸福時刻。因為,這些點點滴滴匯聚起來的,才是構成我們豐富多彩生活的本質。希望每個人都能在繁忙的生活中找到自己的快樂之源,不僅僅為了生存而工作,更為了更好的生活而生活。
????????送你張美圖!希望你開心!
簡介
在Java中,實現發布-訂閱模型可以通過多種方式完成,包括使用內置的并發工具如BlockingQueue
。這里,我們使用LinkedBlockingQueue
來演示一個簡單的發布-訂閱系統,其中發布者將消息放入隊列,而訂閱者從隊列中取出消息進行處理。
步驟 1: 定義消息類
首先,定義一個簡單的消息類,用于發布者和訂閱者傳遞消息。
public class Message {private String content;public Message(String content) {this.content = content;}public String getContent() {return content;}
}
步驟 2: 創建發布者
發布者(Producer)將消息放入共享的BlockingQueue
中
import java.util.concurrent.BlockingQueue;public class Producer implements Runnable {private BlockingQueue<Message> queue;public Producer(BlockingQueue<Message> q) {this.queue = q;}@Overridepublic void run() {// 發送消息for (int i = 0; i < 10; i++) {Message msg = new Message("" + i);try {Thread.sleep(i);queue.put(msg);System.out.println("Produced " + msg.getContent());} catch (InterruptedException e) {Thread.currentThread().interrupt();}}// 發送結束消息Message msg = new Message("exit");try {queue.put(msg);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}
}
步驟 3: 創建訂閱者
訂閱者(Consumer)從BlockingQueue
中取出消息并處理。
import java.util.concurrent.BlockingQueue;public class Consumer implements Runnable {private BlockingQueue<Message> queue;public Consumer(BlockingQueue<Message> q) {this.queue = q;}@Overridepublic void run() {try {Message msg;// 檢查消息內容是否為"exit"while (!(msg = queue.take()).getContent().equals("exit")) {Thread.sleep(10);System.out.println("Consumed " + msg.getContent());}} catch (InterruptedException e) {Thread.currentThread().interrupt();}}
}
步驟 4: 實現發布-訂閱模型
現在,使用一個LinkedBlockingQueue
來連接發布者和訂閱者。
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;public class PubSubService {public static void main(String[] args) {// 創建共享的阻塞隊列BlockingQueue<Message> queue = new LinkedBlockingQueue<>();// 創建并啟動發布者和訂閱者線程Thread producerThread = new Thread(new Producer(queue));Thread consumerThread = new Thread(new Consumer(queue));producerThread.start();consumerThread.start();}
}
在這個簡單的發布-訂閱模型中,Producer
類生成消息并將它們放入隊列,而Consumer
類從隊列中取出并處理這些消息。使用LinkedBlockingQueue
使得這個過程在多線程環境中是線程安全的,同時還處理了生產者和消費者的速率不匹配問題。
------------------------------------------與正文內容無關------------------------------------
?如果覺的文章寫對各位讀者老爺們有幫助的話,麻煩點贊加關注唄!作者在這拜謝了!
混口飯吃了!如果你需要Java 、Python畢設、商務合作、技術交流、就業指導、技術支持度過試用期。請在關注私信我,本人看到一定馬上回復!
這是我全部文章所在目錄,看看是否有你需要的,如果遇到覺得不對地方請留言,看到后我會查閱進行改正。
A樂神-CSDN博客