【问题标题】:Stopping a Runnable while waiting for a connection in a while loop在 while 循环中等待连接时停止 Runnable
【发布时间】:2013-09-28 14:31:15
【问题描述】:

我有一个Runnable 类,它正在等待Socket 连接。我想添加JButton,这会导致它停止等待连接并退出循环。

这是循环

volatile boolean finished = false;

while (!finished) {
    System.out.println("Server Started....");
    clientSocket = serverSocket.accept();    // want to skip this line when the button is pressed
    if (!clientSocket.isClosed() && ServerSettings.getServerStatus() != -1) {
        // start communication
    } else {
        // close connection
    }
}

我查找了这个问题,发现a solution here 退出循环。但这并不能完全解决我的问题。我可以更改finished 变量的值,但要检查新值,我仍然需要跳过等待一次。

任何帮助都是可观的。

【问题讨论】:

  • 顺便说一句:true && !finished == !finished。
  • @Quirliom:谢谢,我已经更新了帖子。

标签: java multithreading sockets loops


【解决方案1】:

您可以调用close() 方法。这将停止等待连接。

【讨论】:

  • 那么,我是否需要在点击时抛出 SocketException,因为它正在等待?
  • 是的。你应该抛出 SocketException。
【解决方案2】:

而不是ServerSocket,使用ServerSocketChannel,它的accept() 方法不会阻塞。来自文档:

public abstract SocketChannel accept() throws IOException

接受与此通道的套接字建立的连接。

如果此通道处于非阻塞模式,则如果没有挂起的连接,此方法将立即返回 null。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-18
    • 2020-04-17
    • 2012-10-14
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2021-08-14
    • 2012-10-13
    相关资源
    最近更新 更多