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

查看:197
本文介绍了如何立即终止套接字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:

  • 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天全站免登陆