2012-04-02 120 views
6

比方说,我开始了一个线程,我有这样的事情:你可以用Future.cancel(true)中断BufferedReader.readLine()吗?

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

      } 

    } 

); 

执行人是ExecutorService的对象和是一个BufferedReader对象

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

回答

10

你可以使用Future.cancel(true)中断BufferedReader.readLine()吗?

全部future.cancel(true)确实是在关联的线程上调用thread.interrupt()。这将导致sleep()wait()操作投掷InterruptedException并将中断一些特殊的NIO channels

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

1

readLine不会丢失InterruptedException因此,如果它运行的线程中断,它将不会受到影响。你需要明确检查线程的中断状态:

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

但如果它阻止在执行readLine,只有这样,才能中断它关闭底层流将抛出IOException。

3

您可以关闭流中以触发IOException。否则,readLine()可能永远阻塞。

我看过使用JavaLangAccess.blockedOn(),但它看起来相当低级别。