Java 如何停止执行从线程的run()方法调用的方法

Java 如何停止执行从线程的run()方法调用的方法,java,multithreading,Java,Multithreading,这是我的帖子:- Thread t=new Thread(){ public void run(){ downloadFile(); } } t.start(); public static void main(){ t.interrupt(); } 这里downloadFile是从服务器下载文件的长期运行方法 问题是,即使t.interrupt被称为downloadFile方法,该方法仍然保持运行,这是不期望的。我希望downloadFile方法在线程中断时立即终止

这是我的帖子:-

Thread t=new Thread(){
  public void run(){
      downloadFile();
  }
}
t.start();

public static void main(){
  t.interrupt();
}
这里downloadFile是从服务器下载文件的长期运行方法 问题是,即使t.interrupt被称为downloadFile方法,该方法仍然保持运行,这是不期望的。我希望downloadFile方法在线程中断时立即终止。我应该如何实现它

谢谢

编辑1:

下面是downloadFile skeleton,它调用rest API获取文件:

void downloadFile(){
  String url="https//:fileserver/getFile"
  //code to getFile method  
}

您需要一些标志来通知线程终止:

public class FileDownloader implements Runnable {
    private volatile boolean running = true;

    public void terminate() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            try {
                downloadFile();
            } catch (InterruptedException e) {
                running = false;
            }
        }

    }
}
大体上:

FileDownloader fileDownloaderRunnable = new FileDownloader();
Thread thread = new Thread(fileDownloaderRunnable);
thread.start();
//terminating thread
fileDownloaderRunnable.terminate();
thread.join();
您的Runnable需要存储一个AtomicBoolean标志来说明它是否被中断

中断方法应该只将标志设置为true

downloadFile方法需要检查下载循环内的标志,如果设置了,则中止下载


这是实现它的唯一干净方法,因为只有downloadFile知道如何安全、干净地中断自身,关闭套接字等。

那么downloadFile是什么样子的呢?downloadFile调用rest API从服务器获取文件。它是如何做到的?您遗漏了最重要的代码,提供了一些无关紧要的代码,这些代码没有解释任何内容。我认为,这与在这里查看其他信息相同。问题在于实际的网络操作。如果有一个套接字阻塞了读取,唯一可靠的方法就是关闭套接字。不一定有任何下载循环,至少是可见的,除非他自己编写原始网络代码。也不需要或使用复制中断功能。假定方法downloadFile完全下载单个文件。因此,您的循环将一遍又一遍地下载该文件,直到您停止它。这真的没有道理。