线程。停止服务器

最近我在做多线程聊天应用程序。现在我正在与服务器斗争。我试图通过引入新字段来停止服务器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;

    }


}


慕侠2389804
浏览 83回答 2
2回答

鸿蒙传说

也许你在这里还有另一个问题(与 Swing 相关):您new JFrame("Chatter")只是创建了一个新的 JFrame 并且不对其执行任何操作。你必须super("Chatter");调用超级构造函数尝试this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)

莫回无

您是否尝试过将您的online财产申报为volatile?private volatile boolean online = true;如果您不将属性声明为volatile,JIT 编译器可以假设您的布尔属性不会被另一个线程更改。所以它可能会优化你的运行方法public void run() {&nbsp; &nbsp; if (!online)&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; while(true) {&nbsp; &nbsp; &nbsp; &nbsp; try(/*...*/) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// ...&nbsp; &nbsp; &nbsp; &nbsp; } catch(/*...*/) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// ...&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java