0

TCP 経由でオブジェクトを受け取るワーカー スレッドへの参照のコレクションを保持するクラスがあります (クライアントごとに 1 つ)。

getMessage()クラスで、いずれかのワーカー スレッドがメッセージを受け取り、それを返すまで待機するメソッドを作成しようとしています。

私が今得たのはポーリングシステムです:

public Object getMessage() {  
    while (true) {  
        for (Worker w : workers.values())  
             if (w.msgNumber() != 0)  
                 return w.getLastMsg();  
        Thread.sleep(100);  
    }  
}

動作しますが、あまりスケーラブルではないと思います。

wait(timeout)各ワーカーで実行できることはわかっていますが、問題は同じままです。

複数のスレッドを待機するある種の待機/通知メカニズムはありますか?

4

2 に答える 2

4

You could look at using a blocking queue for communications between threads. The worker thread would insert into the queue, while the getMessage() function pulls a message from the queue.

于 2012-06-22T21:16:16.873 に答える
0

次のようなものはどうですか:

   try {
        ServerSocket srv = new ServerSocket(port);

        // Wait for connection from client.
        while (true) {
            System.out.println("Listening...");
            // Waits for connection
            new Thread(new ServerWorkerThread(srv.accept())).start(); 

        }
    } catch (IOException e) {
      //handle
    }
于 2012-06-22T21:19:22.990 に答える