亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

線程。停止服務器

線程。停止服務器

慕俠2389804 2023-08-16 17:57:03
最近我在做多線程聊天應用程序?,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 相關):

  1. new JFrame("Chatter")只是創建了一個新的 JFrame 并且不對其執行任何操作。你必須super("Chatter");調用超級構造函數

  2. 嘗試

    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)


查看完整回答
反對 回復 2023-08-16
?
莫回無

TA貢獻1865條經驗 獲得超7個贊

您是否嘗試過將您的online財產申報為volatile?


private volatile boolean online = true;

如果您不將屬性聲明為volatile,JIT 編譯器可以假設您的布爾屬性不會被另一個線程更改。所以它可能會優化你的運行方法


public void run() {

    if (!online)

        return;

    while(true) {

        try(/*...*/) {

           // ...

        } catch(/*...*/) {

           // ...

        }

    }

}


查看完整回答
反對 回復 2023-08-16
  • 2 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號