我有以下代碼:如何中斷此線程?
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()」 塊線程,當主機是錯誤的。如何從另一個線程中斷這段代碼?
中斷它從哪裏? –
來自另一個線程 – mystdeim
我建議使用超時,當主機錯誤/無法訪問。 –