有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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()”会阻塞线程。如何从另一个线程中断此代码


共 (4) 个答案

  1. # 1 楼答案

    ^{}设置超时值。如果超时过期,捕获SocketTimeoutException,并按照您想要的方式恢复或终止程序

  2. # 2 楼答案

    This "con.getInputStream()" blocks thread, when host is wrong. How to interrupt this code from another thread?

    这是一个常见问题。中断线程不会导致readLine(...)方法中断。引用我的回答:

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

    It is important to realize that t.interrupt() only sets the interrupted bit in a thread -- it doesn't actually interrupt the thread's processing per se. A thread can be interrupted at any time safely.

    因此,如果线程在readLine(...)中被阻塞,则无法中断线程。但是,您可以将循环更改为:

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

    正如其他人所提到的,您可以关闭底层InputStream,这将导致readLine()抛出Exception

  3. # 3 楼答案

    一般规则是从“外部”中断不间断线程,即

    • 线程等待连接/流-关闭连接
    • 线程等待挂起进程完成-通过终止进程
    • (不特别是在这种情况下)运行的长循环-通过引入一个布尔变量,该变量从外部设置,并不时在循环内部检查
  4. # 4 楼答案

    不幸的是,你不能中断被一些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.
        }
       }
    ....
    }