处理线程
管理在后台工作的线程的正确方法是什么?
例如,我有一个创建多个线程的活动。我需要执行以下操作:
1)当Application被销毁时销毁所有线程
2) 如果用户离开 Activity,则暂停 Activity 中创建的线程
3)如果 Activity 被销毁,则销毁 Activity 中创建的线程
我想到的唯一一件事是将所有线程变量声明为公共,以便能够在这些事件上发出 t.destroy() 或类似的东西我上面列出的。 首先,我不确定这是否是正确的方法,其次,我不喜欢它,因为我必须更改代码以确保我可以引用我创建的所有线程。
例如,我的 Activity 实例化新对象(例如 LoadImages.class),并且该对象根据要加载的图像数量创建多个线程。线程对于调用活动是不可见的。
那么,我是否必须将线程引用传递给调用活动,或者有什么方法可以知道谁是线程的父级并仅销毁具有特定父级 Activity 的线程?
What is the proper way to manage threads working in the background?
For example, I have Activity that creates several threads. I need to do following:
1) Destroy all threads when Application is destroyed
2) Pause threads created within Activity if user navigate away from Activity
3) Destroy threads created within Activity if Activity is destroyed
The only thing that come to my mind would be to have all threads variables declared as public the to be able to issue t.destroy() or something similar on these events that I listed above.
First, I am not sure if this is right way at all, and secondly, I don't like it because I will have to change code to make sure I can reference all threads I created.
For example, I have situation where my Activity instantiate new object (ex. LoadImages.class) and that objects creates several thread depending on how many images is to be loaded. The threads are not visible from the calling activity.
So, do I have to pass threads references to calling activity, or there is some way to know who is the parent of the thread and destroy only thread with particular parent Activity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于
LoadingImages
我认为有一个简单的解决方案:在LoadingImage
上有一个名为release
的公共方法,该方法将允许它释放自己的资源。如果您的每个活动都在破坏自己的线程,那么我认为您不需要执行步骤 1。
For
LoadingImages
I think there is a simple solution: have a public method onLoadingImage
calledrelease
that will allow it to release its own resources.If each of your activities is destroying its own threads, I don't see the need for your step 1.