简体   繁体   English

你能用Future.cancel(true)中断BufferedReader.readLine()吗?

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

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 is a ExecutorService object and in is a BufferedReader object executor是一个ExecutorService对象,并且是一个BufferedReader对象

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? 但是当我尝试使用future.cancel(true)方法时,即使它返回true,线程似乎仍然在运行,任何人都知道为什么? or in.readLine() cannot be interrrupted this way? 或in.readLine()不能以这种方式中断?

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

All future.cancel(true) does is to call thread.interrupt() on the associated thread. 所有future.cancel(true)都是在关联的线程上调用thread.interrupt() This will cause sleep() and wait() operations to throw an InterruptedException and will interrupt some special NIO channels . 这将导致sleep()wait()操作抛出InterruptedException ,并将中断一些特殊的NIO通道

But chances are your BufferedReader will not be interrupted since it is most likely reading from a "normal" socket or file. 但是很可能你的BufferedReader不会被中断,因为它很可能是从“普通”套接字或文件中读取的。 As you mention, closing the underlying socket from a different thread is the best way to kill such an IO method. 正如您所提到的,从不同的线程关闭底层套接字是杀死这种IO方法的最佳方法。

You can close the in stream to trigger an IOException. 您可以关闭in stream以触发IOException。 Otherwise a readLine() can block forever. 否则readLine()可以永远阻塞。

I have looked at using JavaLangAccess.blockedOn() but it looks rather low level. 我已经看过使用JavaLangAccess.blockedOn()但它看起来相当低级别。

readLine does not throw InterruptedException so it will not be affected if the thread it runs in is interrupted. readLine不会抛出InterruptedException因此如果它运行的线程被InterruptedException ,它将不会受到影响。 You need to explicitly check the interrupted status of the thread: 您需要显式检查线程的中断状态:

        while ((str = in.readLine()) != null)
        {
            if (Thread.interrupted()) {
                //You can deal with the interruption here
            }
        }

But if it blocks while executing readLine , the only way to interrupt it is to close the underlying stream which will throw an IOException. 但是如果它在执行readLine时阻塞,则中断它的唯一方法是关闭将引发IOException的底层流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM