当活动销毁不起作用时Android线程中断
我是 Android 开发新手。我有一个活动,我创建一个线程来加载图像并在 imageView 上刷新它。线程运行“无限循环”。我还想在活动停止时停止线程。您可以在下面的示例中看到我已经实现的内容,但它抛出异常并且线程继续工作或应用程序崩溃。有什么建议吗?
public class myActivity extends Activity{
Thread tr;
.... onCreate(){
bla bla bla
tr = new Thread();
tr.start();
}
.....onDestroy(){
tr.interupt();
}
bla bla bla
}
很抱歉没有编写完整的代码,但我现在不在家,我有代码。 我应该改变什么才能让它停止?
我还尝试了另一个技巧,我设置了一个公共静态布尔值,并在 onDestroy 上将其设置为 false。
在线程中,“无限循环”工作为:
public static Boolean is = true;
in thread:
while (is == true)....
onDestroy:
is = false;
那么,使用这个技巧,由于循环将结束,线程在结束其操作时是否会被杀死?
I'm new to android developing. I have an activity where I create a thread to load an image and refresh it on imageView. The thread runs an "infinite loop". I want to also stop the thread when the activity is stopped. Below you can see in sample what I have implemented but it throws exception and the thread continues to work or the app crashes. Any suggestions?
public class myActivity extends Activity{
Thread tr;
.... onCreate(){
bla bla bla
tr = new Thread();
tr.start();
}
.....onDestroy(){
tr.interupt();
}
bla bla bla
}
Sorry for not writing the full code but I'm not home right now where I have the code.
What should I change to make it stop ok?
I have also tried another trick, where I set a public static boolean and onDestroy I set it false.
In the thread the "infinite loop" wokrs as :
public static Boolean is = true;
in thread:
while (is == true)....
onDestroy:
is = false;
So, with this trick, since the loop will end, will the thread be killed when it has ended it's operations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
线程在其
run
方法完成执行时结束。因此,如果您通过将boolean
设置为false
来中断 while 循环,然后控件到达run
末尾,则线程肯定会完成。事实上,这是在 java 中停止线程的推荐方法。您应该记住的重要一点是始终将由一个线程修改并由另一个线程读取的变量设置为
易失性
,以防止变量缓存等优化破坏您的代码:A thread ends when its
run
method finishes executing. So if you break the while loop by setting theboolean
tofalse
and then the control reaches the end ofrun
, the thread will surely finish. This is in fact the recommended way to stop a thread in java.One important point you should remember is to always set variables that are modified by one thread and read by another one as
volatile
, to prevent optimizations like variable caching from breaking your code:不要使用第一种方法解决您的问题,java线程文档中不推荐这种方法。第二种方法是完成这项工作的最佳方法。现在,在第二种方法中,当您在 onDestroy 方法中将“is”变量设置为 false 时,这将立即中断线程内的 while 循环。现在,在 while 循环之后,如果您编写了任何代码,那么它将继续执行,一旦到达线程代码的末尾,线程将自行停止。
Don't solve your problem using the first approach ,This approach is not recommended in java threads documentation. Your second approach is the best way of doing this job. Now in the second approach when u make your "is" variable as false in onDestroy method, this will immediately break the while loop inside your thread. Now after this while loop If you have written any code then it will continue executing and once it reaches the end of your thread code the thread will stop by itself.