我不完全確定,你想要什麼。我假設你要保證一次只有一個線程訪問一個特定的服務器。
如果你的連接是像一個插座,那麼您可以在一個synchronization statement使用它作爲一個鎖:
private void send(Connection c, Data d) {
synchronized (c) {
// for each connection object, only one thread may be inside this block.
// all other threads wait until the thread currently in this block exits it.
c.send(d);
}
}
// somewhere else ...
Data data = determineDataToSend()
Connection connection = map.get(key);
send(connection, data)
你可以把邏輯還融入了裝飾進行連接。這是連接是否具有一種以上的方法是發送或接收特別有用的(例如,由於您使用的是更高的抽象水平像RMI):
public interface PowerfulConnection {
public void doA();
public int doB(ParameterForB param);
}
public class ConnectionImpl implements PowerfulConnection {
// handles the actual connection
}
/**
* This method is a decorator for PowerfulConnection that synchronizes all method accesses.
*/
public class SynchronizedConnection implements PowerfulConnection {
private PowerfulConnection target;
public SynchronizedConnection(PowerfulConnection target) {
if (target == null) throw new NullPointerException();
this.target = target;
}
public synchronized void doA() {
target.doA();
}
public synchronized int doB(ParameterForB param) {
return target.doB(param);
}
}
如果您正在使用的裝飾方法,那麼你的唯一的事需要改變的是實例創建。相反的:
private void connect(key, connectionParams) {
map.put(key, new ConnectionImpl(connectionParams));
}
使用
private void connect(key, connectionParams) {
map.put(key, new SynchronizedConnection(new ConnectionImpl(connectionParams)));
}
什麼是多服務器? – SLaks 2010-01-01 15:34:26
我的程序連接到很多服務器 – QuanNH 2010-01-01 15:36:46
您使用serversocket作爲服務器嗎? – SjB 2010-01-01 15:37:03