java如何中断这个线程?
我有以下代码:
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 楼答案
用^{} 设置超时值。如果超时过期,捕获
SocketTimeoutException
,并按照您想要的方式恢复或终止程序# 2 楼答案
这是一个常见问题。中断线程不会导致
readLine(...)
方法中断。引用我的回答:因此,如果线程在
readLine(...)
中被阻塞,则无法中断线程。但是,您可以将循环更改为:正如其他人所提到的,您可以关闭底层
InputStream
,这将导致readLine()
抛出Exception
# 3 楼答案
一般规则是从“外部”中断不间断线程,即
# 4 楼答案
不幸的是,你不能中断被一些I/O操作阻塞的线程(除非你使用NIO)
您可能需要(通过另一个线程)关闭读取线程阻塞的流
类似这样: