java - 我可以在线程内强制中断吗?
问题描述
我写了一个类,通过网络发送一些内容。我有一些问题,因为文件发送在 10 多个小时后没有结束,我认为是连接中断。
我想把 sender 方法放到一个不同的线程中,如果它还没有结束,我会在超时后尝试中断它。但问题出在内核类中,我无法在其中输入查询来检查是否检查了 Therad.isinterrupted。
我可以在不要求他通过中断方法终止的情况下截断线程吗?
谢谢你,卢西奥·门奇
解决方案
在这种情况下,好的策略是关闭套接字连接本身,这将导致任何挂起write
的操作中止并抛出SocketException
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#close()
class FileTransfer
{
protected Socket theSocket;
//...
public void sendFile() throws Exception
{
// ...
theSocket = new Socket(...);
// ...
}
public void abortTransfer() throws Exception
{
// This may be called from another thread so do not mark it as synchronized
theSocket.close(); // At this point sendFile() with throw exception SocketException
}
// ...
}
当然,您可能需要添加一些额外的棘手逻辑来处理竞争条件,以便以最通用的方式进行(为了清楚起见,我省略了它)。无论如何,整个想法很简单:从另一个线程关闭套接字,您将write
终止挂起的操作。
推荐阅读
- json - 如何将带有标识符的 JSON 对象解析为打字稿?
- cmake - 如何在 CMake 中安装时使用版本号重命名/修改目标文件?
- python-3.x - python中的if函数。在 break 语句中出现错误
- c# - C# ToolTip 语言在运行时更改
- python - 获取 ValueError:参数的类型不受支持,我尝试了所有数据类型
- php - 如何从 ajax 响应数据中获取 php 变量数据
- javascript - SHA256 的 ABAP 字符串与 SAPUI5/Javascript 不同
- sql - Athena/Presto:复杂结构/数组
- service - 将 ExoPlayer 实例从活动传递到绑定服务?
- charts - 页面上的 3 个 Google 图表不显示任何内容