2012-04-02 118 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(),但它看起來相當低級別。