首页 > 解决方案 > 我可以在线程内强制中断吗?

问题描述

我写了一个类,通过网络发送一些内容。我有一些问题,因为文件发送在 10 多个小时后没有结束,我认为是连接中断。

我想把 sender 方法放到一个不同的线程中,如果它还没有结束,我会在超时后尝试中断它。但问题出在内核类中,我无法在其中输入查询来检查是否检查了 Therad.isinterrupted。

我可以在不要求他通过中断方法终止的情况下截断线程吗?

谢谢你,卢西奥·门奇

标签: javamultithreading

解决方案


在这种情况下,好的策略是关闭套接字连接本身,这将导致任何挂起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终止挂起的操作。


推荐阅读