我有兩個條件,一個在另一個裏面,用布爾值來控制它們。基本上,一個是終止一個共享,另一個是傾聽連接。用戶可以選擇禁用共享,在這種情況下,服務器會停止監聽,但不會終止。如果用戶選擇終止,則兩個布爾值都設置爲false,並結束循環。爲什麼不重新評估條件?
這是我的代碼:
public void run() {
while (!terminate) {
while (listening) {
try {
// accept connection -> create a new thread for each client
ClientServerShareInstance clientServerShareInstance = new ClientServerShareInstance(serverSocket.accept(), ui);
Thread clientServerThread = new Thread(clientServerShareInstance);
clientSockets.add(clientServerShareInstance);
connectedClients++;
clientServerThread.start();
} catch (IOException ex) {
}
}
}
}
public void closeAllClientConnections() {
for (Iterator it = clientSockets.iterator(); it.hasNext();) {
ClientServerShareInstance clientServerShareInstance = (ClientServerShareInstance) it.next();
clientServerShareInstance.closeAllConnections();
it.remove();
}
try {
this.serverSocket.close();
} catch (IOException ex) {}
this.setActive(false);
this.connectedClients = 0;
}
public void openConnection() {
try {
serverSocket = new ServerSocket(portNumber, 0, Inet4Address.getLocalHost());
setActive(true);
} catch (IOException ex) {}
}
}
的closeAllClientConnections()
方法禁用份額(不終止它),而且份額openConnection()
重新啓用。
問題是,如果我禁用共享,它應該循環terminate
而無限期地cicle,測試值listening
。當我將listening
設置爲true
時,它應該在循環中重新輸入第二個字符,然後再次開始監聽,因爲我打開了服務器套接字(儘管它與此無關,我只是說它必須再次被初始化,因爲我關閉了它當我禁用共享)。但是,禁用後,即使調用openConnection()
,也不會租用listening
循環。
有人知道這裏有什麼問題嗎?
'SETACTIVE( ...)'設置'聽'的價值? – Gray
不,他們只是在我的班級裏宣佈爲常規私人布爾人。我沒有使用volatile,因爲我認爲對象是在多個線程之間共享的,而且我不需要鎖定,因爲它不是一個複雜的操作,多個線程同時「爭奪」訪問權限。 – swiftcode
@Gray是的,它的確如此。它只是這個變量的二傳手。 – swiftcode