[英]How to synchronize the pass of two queues to thread constructor?
我正在嘗試以級聯方式處理傳遞給兩個線程的兩個隊列的同步。 所以我有兩個線程,ServerThread偵聽來自客戶端的連接,以及ConnectedThread,它是在服務器線程從客戶端接受連接的情況下創建的。 我不知道如何將這些隊列的傳遞同步到ConnectedThread類的線程構造函數。 是否應該同步這些隊列? 我不知道什么是最佳做法。 我試圖通過以下方式做到這一點:
synchronized (this) {
new ConnectedThread(socket, inQueue, outQueue).start();
}
並通過:
synchronized (inQueue) {
synchronized (outQueue) {
new ConnectedThread(socket, inQueue, outQueue).start();
}
}
一切當然都在ServerThread類的線程的"run()"
方法中。
代碼中的所有內容如下所示:
private class ServerThread extends Thread {
public ServerThread(int port, Queue<ThreadMessage> in,
Queue<ThreadMessage> out) throws Exception {
// TODO Auto-generated constructor stub
setName("ServerThread");
try {
server = new ServerSocket(port);
synchronized (in) {
synchronized (out) {
inQueue = in; outQueue = out;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
throw new Exception();
}
}
private ServerSocket server;
private Queue<ThreadMessage> inQueue, outQueue;
private boolean running = true;
@Override
public void run() {
// TODO Auto-generated method stub
while (running) {
try {
Socket socket = server.accept();
synchronized (inQueue) {
synchronized (outQueue) {
try {
new ConnectedThread(socket, inQueue, outQueue)
.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
SeverThread類的線程是在同步方法內部創建的。
public synchronized void startServer(int port, Queue<ThreadMessage> in,
Queue<ThreadMessage> out) throws Exception {
serverThread = new ServerThread(port, in, out);
serverThread.start();
}
有什么建議如何正確處理嗎?
預先感謝。
PS對不起,我的英語。 PS隊列是LinkedList
實例
您不需要將Queue
實例的引用的分配同步到類成員。
您需要同步的是您在隊列上執行的操作,例如poll()
或offer()
。
同步有什么用? 好吧,當有多個線程(在您的示例ConnectedThread
)與一個共享庫(在您的示例中,輸入和輸出隊列)一起工作時,您必須同步操作,以便應用程序以線程安全的方式執行操作。
示例:如果兩個線程想從隊列中讀取,並且兩個線程都看到隊列不為空(隊列包含一個元素),則它們都將對它調用poll
,但是只有一個線程將從隊列中獲取元素。 另一個線程將為null
並在您的邏輯中引起問題。 因此,您必須同步隊列的讀寫操作。
同步僅在訪問對象(例如,瀏覽或修改隊列)時有用,而對引用(即分配或參數傳遞)無用。
您發布的代碼未提及如何處理隊列。
還考慮使用Java SE API中存在的並發隊列實現:“ 隊列實現”教程頁面
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.