2012-06-02 45 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方法