【问题标题】:How to stop execution of method called from run() method of thread如何停止从线程的run()方法调用的方法的执行
【发布时间】:2017-04-18 08:47:39
【问题描述】:

这是我的主题:-

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

public static void main(){
  t.interrupt();
}

这里downloadFile() 是长时间运行的方法(从服务器下载文件) 问题是,即使 t.interrupt() 被称为 downloadFile() 方法仍然会继续运行,这不是预期的。我希望 downloadFile() 方法在线程中断后立即终止。我应该如何实现它?

谢谢。

编辑1:

这里是调用其余 API 来获取文件的 downloadFile() 框架:

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

【问题讨论】:

标签: java multithreading


【解决方案1】:

您的Runnable 需要存储一个AtomicBoolean 标志来说明它是否已被中断。

interrupt 方法应该只是将标志设置为 true。

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

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

【讨论】:

  • 问题出在实际网络操作上。如果读取时出现套接字阻塞,阻止它的唯一可靠方法是关闭套接字。不一定有任何“下载循环”(至少可见),除非他自己编写原始网络代码。也不需要(或使用)复制中断功能。
【解决方案2】:

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

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();

【讨论】:

  • 大概downloadFile()这个方法完全下载了一个文件。因此,您的循环会一遍又一遍地下载文件,直到您停止它。这真的没有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
相关资源
最近更新 更多