2013-10-31 68 views
2

我有以下代碼:如何中斷此線程?

public class Net { 
    public static void main(String[] args) {   
     Runnable task = new Runnable() {    
      @Override 
      public void run() { 
       String host = "http://example.example"; 
       try { 
        URL url = new URL(host); 
        StringBuilder builder = new StringBuilder();      
        HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
        try(BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { 
         String line; 
         while (null != (line = in.readLine())) builder.append(line); 
        }   
        out.println("data: " + builder.length()); 
        con.disconnect(); 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     }; 
     Thread thread = new Thread(task); 
     thread.start(); 
     thread.interrupt(); 
    } 
} 

這種 「con.getInputStream()」 塊線程,當主機是錯誤的。如何從另一個線程中斷這段代碼?

+1

中斷它從哪裏? –

+1

來自另一個線程 – mystdeim

+0

我建議使用超時,當主機錯誤/無法訪問。 –

回答

1

setReadTimeout設置超時值。如果超時到期,趕上SocketTimeoutException,並以您想要的方式恢復或終止程序。

+0

無論如何,我得到「UnknownHostException」 – mystdeim

3

的一般規則是從「外部」中斷不間斷線程,即

  • 線程等待連接/流 - 通過關閉連接。
  • 線程正在等待掛斷進程完成 - 通過終止進程。
  • (並非特指本例)一個正在運行的長循環 - 通過引入一個布爾變量,該變量從外部設置並在循環內不時進行檢查。
+0

+1運行long循環也可以使用'while(!Thread.currentThread()。isInterrupted){...}來終止' – Gray

0

這個「con.getInputStream()」阻塞線程,當主機錯誤時。如何從另一個線程中斷這段代碼?

這是常見問題解答。中斷一個線程而不是導致readLine(...)方法被中斷。從我的答案在這裏引用:

I want my thread to handle interruption, but I can't catch InterruptedException because it is a checked exception

意識到t.interrupt()只設置中斷位中的一個線索是非常重要的 - 它實際上並沒有中斷線程的處理本身。線程可以在任何時候安全地中斷。

因此,如果線程在readLine(...)中被阻止,則無法中斷該線程。但是你可以改變你的循環,是這樣的:

while (!Thread.currentThread().isInterrupted()) { 
    String line = in.readLine(); 
    if (line == null) { 
     break; 
    } 
    builder.append(line); 
} 

你可以像其他人所說的,封閉的基本InputStream這將導致readLine()拋出Exception

1

不幸的是,你不能中斷被某些I/O操作阻塞的線程(除非你使用NIO)。
您可能需要關閉讀取線程阻塞的流(由另一個線程)。
這樣的事情:

public class Foo implements Runnable{ 
private InputStream stream; 
private int timeOut; 
.... 
    public void run(){ 
    Thread.sleep(timeOut); 
    if(<<ensure the victim thread still is stuck>>){ 
     stream.close();//this will throws an exception to the stuck thread. 
    } 
    } 
.... 
}