簡體   English   中英

如何停止執行從線程的run()方法調用的方法

[英]How to stop execution of method called from run() method of thread

這是我的主題:

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

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

在這里, downloadFile()是一種長期運行的方法(從服務器下載文件),問題是,即使t.interrupt()被稱為downloadFile()方法仍然保持運行,這是無法預期的。 我希望downloadFile()方法在線程中斷后立即終止。 我應該如何實現呢?

謝謝。

編輯1:

這是downloadFile()骨架,它調用其余的API來提取文件:

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

您的Runnable需要存儲一個AtomicBoolean標志,以表明它是否已被中斷。

interrupt方法應將標志設置為true。

downloadFile()方法需要檢查下載循環中的標志,如果已設置,則中止下載。

像這樣的東西是唯一實現它的干凈方法,因為只有downloadFile知道如何安全,干凈地中斷自身,關閉套接字等。

您需要一些標志來通知線程有關終止的信息:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM