中断正在等待来自套接字的 IO 的线程?
我有一个应用程序可以侦听指定主机名和端口上的传入连接。使用 listen()
方法调用监听(见下文),该方法使用 ServerSocket.accept()
持续等待传入连接,创建一个新的 Thread
来处理输入流。
private ServerSocket serverSocket;
private Thread listenerThread;
public void listen() throws IOException {
this.listenerThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Socket socket = TheServerClass.this.serverSocket.accept();
// Create new thread to handle the incoming connection
}
catch (IOException exc) { }
}
}
});
this.listenerThread.start();
}
现在我想停止listenerThread
的运行。但是当我调用 this.listenerThread.interrupt()
时,这不起作用。
我以为你可以通过中断线程来停止它,那么为什么这不起作用呢?
(注意:一个可能的解决方案是使用 this.serverSocket.close()
关闭 ServerSocket
,但是可以用 来完成吗?中断()或其他什么?)
I have an app that listens to incoming connections on a specified hostname and port. The listening is invoked with the method listen()
(see below), which waits constantly for an incoming connection using ServerSocket.accept()
, creating a new Thread
to handle the input stream.
private ServerSocket serverSocket;
private Thread listenerThread;
public void listen() throws IOException {
this.listenerThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Socket socket = TheServerClass.this.serverSocket.accept();
// Create new thread to handle the incoming connection
}
catch (IOException exc) { }
}
}
});
this.listenerThread.start();
}
Now I want to stop the running of listenerThread
. But when I call this.listenerThread.interrupt()
, this doesn't work.
I thought you can stop a thread by interrupting it, so why isn't that working?
(Notice: A possible solution is to close the ServerSocket
using this.serverSocket.close()
, but can it be accomplished with interrupt()
or something?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用
serverSocket.close()
,我猜因为你还没有进行IO - 你不能中断它,并且由于
accept()
不会抛出InterruptedException,你就赢了无法打断它。线程被中断,但是您必须自己检查该标志Thread.isInterrupted()
。请参阅如何中断 ServerSocket Accept() 方法? 。
Call
serverSocket.close()
,I guess since you are not doing IO yet - you can not interrupt it, and since the
accept()
doesn't throw InterruptedException you won't be able to interrupt it. The thread is interrupted, but that flag you have to check for yourselfThread.isInterrupted()
.See How can I interrupt a ServerSocket accept() method?.
答案就在问题里。您需要关闭套接字。这是使用
serverSocket.close()
完成的。Thread.interrupt()
不关心套接字。The answer is in the question. You need to close the socket. It's done using
serverSocket.close()
.Thread.interrupt()
doesn't care about sockets.使用这个:
并从
listen()
方法中调用线程的setStop()
方法。Use this:
and from the
listen()
method just callsetStop()
method of the thread.