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
How to stop thread safely in android?
提问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
回答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);
}
}