[英]Java - can two threads on client side use the same input stream from server?
我正在針對Java客戶端/服務器應用程序開發一套非常特定的規則,以了解如何開發它。 服務器創建一個ClientHandler
實例,該實例具有到客戶端套接字的輸入和輸出流,並且它們之間的任何輸入和輸出都是由客戶端GUI中的事件觸發的。
我現在在服務器端添加了功能,該功能將向所有連接的客戶端發送定期更新(通過將來自ClientHandlers
每個創建的PrintWriter
對象存儲在ArrayList<PrintWriter>
)。 我需要一種等效的機制來處理這些消息的客戶端,並且被告知這需要在第二個客戶端線程中發生,該線程的run()
方法使用do...while(true)
循環直到客戶端斷開連接。
到目前為止,這一切對我來說都是有意義的,我正在苦苦掙扎的事實是,兩個線程將必須共享一個輸入流,並且實際上“忽略”了它們處理的類型以外的任何消息。 在我的腦海中,它看起來應該像這樣:
假設來自服務器的每條消息在所有消息上均發送一個boolean
值true
,而在一條消息中向單個客戶端發送值false
boolean
值...
Existing Client Thread
//method called from actionPerformed(ActionEvent e)
//handles server response to bid request
public void receiveResponse()
{
//thread should only process to-specific-client messages
if (networkInput.nextBoolean() == false)
{
//process server response...
}
}
Second Client-side Thread
//should handle all messages set to all clients
run()
{
do {
if (networkInput.nextBoolean() == true)
{
//process broadcasted message...
} while (true);
}
因為他們需要使用相同的輸入流,所以我顯然會添加一些synchronized
, wait/notify
調用,但是總的來說,我想在這里做什么? 還是試圖從同一個輸入流中讀取的兩個線程會相互干擾太多?
請讓我知道你的想法!
謝謝馬克
您可以做到,盡管測試和正確設置很復雜。 “太多”多少取決於您。 一個更簡單的解決方案是讓讀取器線程將消息傳遞給兩個工作線程。
ExecutorService thread1 = Executors.newSingleThreadedExecutors();
ExecutorService thread2 = Executors.newSingleThreadedExecutors();
while(running) {
Message message = input.readMessage();
if (message.isTypeOne())
thread1.submit(() -> process(message));
else if (message.isTypeTwo())
thread2.submit(() -> process(message));
else
// do something else.
}
thread1.shutdown();
thread2.shutdown();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.