你能用Future.cancel(true)中断BufferedReader.readLine()吗? [英] Can you interrupt BufferedReader.readLine() with Future.cancel(true)?

查看:359
本文介绍了你能用Future.cancel(true)中断BufferedReader.readLine()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一个帖子,我有类似的东西:

Let's say I started a thread and I have something like this:

 ...//initiate all the socket connection
 future = executor.submit
 (  new Runnable()
    {   public void run()
        {   ...
            ...      
            while ((str = in.readLine()) != null)
            {  //do something here

            }

    }

 );

executor是一个ExecutorService对象,并且是一个BufferedReader对象

executor is a ExecutorService object and in is a BufferedReader object

我知道你可以从另一个线程关闭套接字来中断这个线程。但是当我尝试使用future.cancel(true)方法时,即使它返回true,线程似乎仍然在运行,任何人都知道为什么?或者in.readLine()不能以这种方式中断?

I know you can close the socket from a different thread to interrupt this thread. But when I try to use future.cancel(true) method, even though it returns true, the thread seems still running, anybody know why? or in.readLine() cannot be interrrupted this way?

推荐答案


你能否中断BufferedReader.readLine ()with Future.cancel(true)?

Can you interrupt BufferedReader.readLine() with Future.cancel(true)?

所有 future.cancel(true)的确是在关联的线程上调用 thread.interrupt()。这将导致 sleep() wait()操作抛出 InterruptedException 并将中断一些特殊的 NIO渠道

All future.cancel(true) does is to call thread.interrupt() on the associated thread. This will cause sleep() and wait() operations to throw an InterruptedException and will interrupt some special NIO channels.

但很可能你的 BufferedReader 不会被打断,因为它很可能是从普通套接字或文件。正如您所提到的,从不同的线程关闭底层套接字是杀死这种IO方法的最佳方法。

But chances are your BufferedReader will not be interrupted since it is most likely reading from a "normal" socket or file. As you mention, closing the underlying socket from a different thread is the best way to kill such an IO method.

这篇关于你能用Future.cancel(true)中断BufferedReader.readLine()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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