Java 如何在android中安全地停止线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4222726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:45:12  来源:igfitidea点击:

How to stop thread safely in android?

javaandroid

提问by Srinivas

how can I stop threads safely?

如何安全地停止线程?

 downloadThread = new Thread(new Runnable() {

   @Override
   public void run() {

  });
  downloadThread.start();
 }

回答by dutt

The easiest one seem to be setting isRunning to false.

最简单的似乎是将 isRunning 设置为 false。

回答by Ashis

Instead of using normal thread to do background jobs if u will use Android sdk's AsyncTask, there you can find a cancel().

而不是使用正常的线程来执行后台作业如果u将采用Android SDK的的AsyncTask,那里你可以找到一个cancel()

回答by Vikram Bodicherla

Interrupt the thread. In the run()method of the thread, check the value of isInterrupted()at the end of different logical blocks.

中断线程。在run()线程的方法中,检查isInterrupted()不同逻辑块末尾的值。

For instance, say your run()method can be broken up into three logical steps - creating a network connection, downloading an image and saving the image to a file. At the end of each of these steps, check for isCancelled()and stop the operation discarding all state at that point.

例如,假设您的run()方法可以分解为三个逻辑步骤 - 创建网络连接、下载图像并将图像保存到文件。在这些步骤中的每一步结束时,检查isCancelled()并停止操作并在该点丢弃所有状态。

class NetworkFetcherTask extends AsyncTask<String, Void, Void>{
    public void doInBackground(String... params){
       String url = params[0];

       //Open connection if not cancelled
       if(isCancelled()){
           conn.close();
           return;
       }
       NetworkConnection conn = new NetworkConnection();


       //Download the image if not cancelled
       if(isCancelled()){
           conn.close();
           result.discard();
           return;
       }
       NetworkResult result = conn.fetchUrl(url);
       conn.close();

       //Save the image to a file if not cancelled
       if(isCancelled()){
          result.discard();
          return;
       }
       File file = new File();
       file.dump(result);
    }
}