处理线程

发布于 2024-10-31 11:56:10 字数 494 浏览 1 评论 0原文

管理在后台工作的线程的正确方法是什么?

例如,我有一个创建多个线程的活动。我需要执行以下操作:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梓梦 2024-11-07 11:56:10

对于 LoadingImages 我认为有一个简单的解决方案:在 LoadingImage 上有一个名为 release 的公共方法,该方法将允许它释放自己的资源。

如果您的每个活动都在破坏自己的线程,那么我认为您不需要执行步骤 1。

For LoadingImages I think there is a simple solution: have a public method on LoadingImage called release 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文