2012-06-02 37 views
0

有拍賣服務器接受客戶端,併爲每個套接字連接一個新的線程服務客戶端。每個線程都有它的協議。服務器只有一個拍賣對象的實例。 Auction對象保存了對象的列表LotAuction對象作爲參數傳遞給客戶端線程。 Protocol必須有辦法投標並以某種方式通知所有客戶線程。方法存在於Lot中,它對出價列表進行出價。下一步是通知所有客戶端線程形式makeBid的方法。最佳做法是什麼? enter image description here如何使用共享資源與其他線程通信?

我試圖在Thread中使用一個字段(MSG)來保存消息。線程檢查是否!MSG.isEmpty()run()。如果!MSG.isEmpty()然後ClientThread打印到此套接字MSG。我認爲有一個更好的解決方案。


public class ClientServiceThread extends Thread { 
public String PRINT_NEW_MSG = ""; 
while (m_bRunThread) { 

       if(!PRINT_NEW_MSG.isEmpty()){ 
        out.println("PRINT_NEW_MSG: "+PRINT_NEW_MSG); 
        PRINT_NEW_MSG = ""; 
       String clientCommand = in.readLine(); 
           ... 
      } 
} 
+0

是否有任何特殊的原因,您不能讓線程等待'BlockingQueue',也許是出價消息? –

+1

這是你的領域的好主意。我更喜歡所有客戶都會被告知的觀察員。所有客戶都需要在觀察員身上註冊。只有一個實例 - 比如你的服務器對象是一個好主意。 (用觀察者擴展你的服務器)。 [鏈接] http://en.wikipedia.org/wiki/Observer_pattern – glenn

回答

1

您可以創建一個訂閱設計,只要客戶對拍賣品進行出價,就會調用lotUpdated()方法。每個ClientThread將訂閱它想要通知的Lots

public class Lot { 
    private List<ClientThread> clients = new ArrayList<ClientThread>(); 
    private List<Integer> bids = new ArrayList<Integer>(); 

    public synchronized void subscribe(ClientThread t){ 
    clients.add(t); 
    } 

    public synchronized void unsubscribe(ClientThread t){ 
    clients.remove(t); 
    } 

    public synchronized void makeBid(int i){ 
    bids.add(i); 
    for (ClientThread client : clients){ 
     client.lotUpdated(this); 
    } 
    } 
} 

public ClientThread { 
    public void lotUpdated(Lot lot){ 
    //called when someone places a bid on a Lot that this client subscribed to 
    out.println("Lot updated"); 
    } 
} 
+0

我有問題,其中ClientThread等待套接字輸入形式用戶* String clientCommand = in.readLine(); *和不能執行「lotUpdated」,直到用戶發送信息? –

+1

不,這不應該是一個問題。會發生什麼情況是''lotUpdated()'將在與'in.readLine()'上阻塞的線程不同的線程中調用。 – Michael

1

你可以更好的使用同步此對象的 「m​​akeBid」 的方法。然後在makeBid的末尾調用notifyAll方法