为了账号安全,请及时绑定邮箱和手机立即绑定

线程。停止服务器

线程。停止服务器

慕侠2389804 2023-08-16 17:57:03
最近我在做多线程聊天应用程序。现在我正在与服务器斗争。我试图通过引入新字段来停止服务器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 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信