如何立即终止阻塞套接字 IO 操作的线程? [英] How to terminate a thread blocking on socket IO operation instantly?

查看:52
本文介绍了如何立即终止阻塞套接字 IO 操作的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java上下文中,我创建了一个新线程来在打开GUI窗口时读取网络输入,当我关闭窗口时,我想释放套接字资源并立即终止线程.现在我正在使用 setSoTimeout 方法,但我不想等待超时异常.有人可以给一些建议吗?谢谢!

In the context of Java, I create a new thread to read network input when open a GUI window, and when i close the window, i want to release the socket resource and terminate the thread immediately. Now i am using setSoTimeout method, but i don't want to wait the timeout exception. Could anybody give some suggestion? Thanks!

推荐答案

有(可能)三种方法来做到这一点:

There are (potentially) three ways to do this:

  • 调用Socket.close() 将关闭关联的 InputStreamOutputStream 对象,并导致任何线程在 Socket 或(关联的) 流操作被解除阻塞.根据 javadoc,对套接字本身的操作将抛出 SocketException.

  • Calling Socket.close() on the socket will close the associated InputStream and OutputStream objects, and cause any threads blocked in Socket or (associated) stream operations to be unblocked. According to the javadoc, operations on the socket itself will throw a SocketException.

调用Thread.interrupt() 将(在某些未指定的情况下)中断阻塞 I/O 操作,导致它抛出一个 InterruptedIOException.

注意警告.显然,interrupt()"方法不适用于大多数"现代 Java 平台.(如果其他人有时间和兴趣,他们可以调查这种方法的工作环境.但是,行为是特定于平台的这一事实应该足以说明您应该只在只需要您的应用程序时使用它在特定平台上工作.此时您可以轻松地为自己尝试".)

第三种可能的方法是调用 Socket.shutdownInput() 和/或 Socket.shutdownOutput().javadocs 没有明确说明当前被阻塞的读和/或写操作会发生什么,但认为它们会解除阻塞并抛出异常并不是没有道理的.但是,如果 javadoc 没有说明会发生什么,则应假定行为是特定于平台的.

A possible third way to do this is to call Socket.shutdownInput() and/or Socket.shutdownOutput(). The javadocs don't say explicitly what happens with read and/or write operations that are currently blocked, but it is not unreasonable to think that they will unblock and throw an exception. However, if the javadoc doesn't say what happens then the behavior should be assumed to be platform specific.

这篇关于如何立即终止阻塞套接字 IO 操作的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆