有拍卖服务器接受客户端,并为每个套接字连接建立一个新线程来服务客户端。每个线程都有它的协议。服务器只有一个Auction对象实例。 Auction
对象保存Lot
对象的列表。 Auction
对象作为参数传递给客户端线程。 Protocol
必须有一种方法可以出价,并以某种方式通知所有客户端线程。 makeBid
方法存在于Lot
中,并将出价放入出价列表。下一步是通知所有客户端线程表单makeBid
方法。最佳做法是什么?
我试图在线程中使用字段(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();
...
}
}
最佳答案
您可以创建一个订阅设计,每当客户对拍品出价时,该订阅设计就会调用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");
}
}
关于java - 如何使用共享资源与其他线程通信?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10865756/