有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程在Java中干净地停止线程侦听serversocket

我正在开发一个程序,其中主线程初始化一个侦听器线程,以侦听到serverSocket的传入连接

    /*
     * run - this will set up the server so that it is ready to listen.
     */
    public void run( serverVariables servVar, storageManager writer, storageVariables write, CoreVariables coreVar, serverFunctions serv, SQLFunctions SQL, SQLvariables SQLvar, netFunctions conn, netVariables netVar) {
        ControlFunctions cntrl = new ControlFunctions();
        util.doCommand("ifconfig eth0 " + servVar.ip);
        ListenerThread listen = new ListenerThread(servVar, coreVar, writer, serv, write, SQL, SQLvar, util);
        try {
            servVar.servSocket = new ServerSocket(servVar.port);
            listen.start();
            cntrl.getInput(util, clr.YELLOW, SQL, SQLvar, listen, conn, netVar);
        } catch (IOException e) {
            System.out.println("Could not read input stream");
            e.printStackTrace();
        }
    }

然后等待来自服务器管理员的输入(在cntrl.getInput()中)。这很好,但是我试图从getInput实现的主要功能是“halt”,它应该检查没有连接,然后停止侦听器和它本身

以下是侦听器线程:

   package server;

import java.io.IOException;

import net.netFunctions;
import net.netVariables;
import core.CoreVariables;
import utl.utilFunctions;
import utl.color;
import server.serverVariables;
import store.storageManager;
import store.storageVariables;
import conn.SQLFunctions;
import conn.SQLvariables;

public class ListenerThread extends Thread {
    color clr = new color();
    CoreVariables coreVar = new CoreVariables();
    utilFunctions util = new utilFunctions();
    netVariables netVar = new netVariables();
    storageManager writer = new storageManager();
    netFunctions conn = new netFunctions();
    storageVariables write = new storageVariables();
    serverFunctions serv = new serverFunctions();
    serverVariables servVar = new serverVariables();
    SQLFunctions SQL = new SQLFunctions();
    SQLvariables SQLvar = new SQLvariables();
    message msg = new message();

    public ListenerThread(serverVariables servVar, CoreVariables coreVar,
            storageManager writer, serverFunctions serv,
            storageVariables write, SQLFunctions SQL, SQLvariables SQLvar,
            utilFunctions util) {
        super("ListenerThread");
        this.coreVar = coreVar;
        this.util = util;
        this.writer = writer;
        this.write = write;
        this.serv = serv;
        this.servVar = servVar;
        this.SQL = SQL;
        this.SQLvar = SQLvar;
    }

    public void run() {
        util.outColored("Listener thread started", clr.CYAN);
        while (true) {
            try {
                new ConnectionThread(clr.GREEN, servVar.servSocket.accept(),
                        coreVar, util, writer, write, serv, servVar, SQL,
                        SQLvar).start();
            } catch (IOException e) {
                System.out.println("Failed to accept");
            }
        }
    }
}

以及haltServer功能:

private boolean haltServer(SQLFunctions SQL, SQLvariables SQLvar, utilFunctions util, String color, ListenerThread listen, netFunctions conn, netVariables netVar) {
    Socket s = null;
    boolean success = false;
    String result = null;
    int count = 0;
    //check for open connections
    SQL.doQuery("SELECT * FROM Clients WHERE Status != 0", SQLvar);
    try {
        while(SQLvar.resultSet.next()) {
            result = SQLvar.resultSet.getString("ClientID");
            util.outColored("Client " + result + " is still connected", color);
            count++;
        }
        if(count == 0) {
            listen.stop();
            success = true;
        }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return success;
}

我知道stop被贬低了,并考虑使用interrupted()作为标志,但我认为由于serverSocket的原因,这不起作用。accept()调用

想法


共 (1) 个答案

  1. # 1 楼答案

    使用布尔标志表示是否应中断:

    private volatile boolean stop = false;
    

    然后创建一个名为kill(不能停止)的方法,将标志设置为true,然后关闭ServerSocket:

    public voic kill() {
        stop = true;
        serverSocket.close();
    }
    

    然后,在catch块中,在将ServerSocket接收到套接字的代码行中,几乎完成了以下操作:

    try {
       //accept server socket
    } catch(IOException e) {
        if(stop)
            return;
        e.printStackTrace();
    }
    

    因此,当您关闭ServerSocket时,它不会打印错误,而是简单地停止尝试接受连接。最后一件事,将while循环更改为:

    while(!stop) { ...
    

    只是为了确保它能正常退出

    事实上,我的电脑上有一台服务器是用Java运行的,它使用以下代码:

        threadHandler = new ThreadPoolExecutor( maxThreads, maxThreads, 1, TimeUnit.MINUTES,
                new ArrayBlockingQueue<Runnable>( maxThreads, true ) );
        while (!serverTerminated) {
            try {
                final Socket connectionSocket = serversocket.accept();
                SocketHandler handler = new SocketHandler( this, connectionSocket );
                threadHandler.submit( handler );
            } catch (IOException e) {
                if (!serverTerminated)
                    e.printStackTrace();
            }
        }