最近我在做多線程聊天應用程序?,F在我正在與服務器斗爭。我試圖通過引入新字段來停止服務器online,但這沒有幫助。import view.ChatHub;import java.io.IOException;import java.io.PrintWriter;import java.lang.reflect.Array;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.Set;import java.util.HashSet;import java.util.Scanner;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ChatServer extends Thread { // All client names, so we can check for duplicates upon registration. private static Set<String> names = new HashSet<>(); // The set of all the print writers for all the clients, used for broadcast. private static Set<PrintWriter> writers = new HashSet<>(); private ChatHub frame; private int port; private boolean online; private ExecutorService pool; public ChatServer(int port) throws IOException { System.out.println("The chat server is running..."); this.frame = new ChatHub(this); this.port = port; this.online = true; this.pool = Executors.newFixedThreadPool(500); this.start(); } @Override public void run() { while (this.online) { try (ServerSocket listener = new ServerSocket(this.port)) { this.pool.execute(new Handler(listener.accept(), this.names, this.writers)); } catch (IOException e) { e.printStackTrace(); } } } public void stopChatServer() { this.pool.shutdown(); this.online = false; } public Set<String> getNames() { return this.names; } public Set<PrintWriter> getWriters() { return this.getWriters(); } public ChatHub getFrame() { return this.frame; } public int getPort() { return this.port; }}
2 回答

鴻蒙傳說
TA貢獻1865條經驗 獲得超7個贊
也許你在這里還有另一個問題(與 Swing 相關):
您
new JFrame("Chatter")
只是創建了一個新的 JFrame 并且不對其執行任何操作。你必須super("Chatter");
調用超級構造函數嘗試
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

莫回無
TA貢獻1865條經驗 獲得超7個贊
您是否嘗試過將您的online財產申報為volatile?
private volatile boolean online = true;
如果您不將屬性聲明為volatile,JIT 編譯器可以假設您的布爾屬性不會被另一個線程更改。所以它可能會優化你的運行方法
public void run() {
if (!online)
return;
while(true) {
try(/*...*/) {
// ...
} catch(/*...*/) {
// ...
}
}
}
添加回答
舉報
0/150
提交
取消