在Android的活动/服务多个线程多个、线程、Android

2023-09-12 05:27:34 作者:涅盘 nirvana

我有一个Android应用程序,其中以列表形式显示在列表中的每个元素,我在一个单独的线程从网络中加载图像。因此,如果有8个项目在列表视图中显示,活动将尝试触发8不同的线程,每个列表项加载的图像。当你向下滚动列表,线程数会在previous线程还没有执行完毕增加。

I have an android app, where in a list view for each element in list, I load an image from web in a separate thread. So if there are 8 items displayed in list view, activity will try to fire 8 different threads, one for each list item to load an image. As you scroll down the list, the number of threads may increase if the previous threads haven't finished executing.

我很好奇,想知道有多少并发线程可以并行一个Android应用程序执行?是否有限制?我不希望这些线程引起ANR通过互联网连接速度较慢,因为它们是独立的?但似乎ANR确实发生,可能是这是因为应用程序/设备上的资源低位运行,所以在产卵UI一个新的活动需要超过5秒,这导致了ANR?

I am curious to know how many simultaneous threads can a single android app execute in parallel? Is there a limit? I wouldn't expect these threads to cause a ANR over slow internet connection as they are independent? But it seems that ANR does happen and may be it's because app/device run low on resources, so spawning a new activity in UI takes more than 5 seconds which results in an ANR?

任何线索,我怎么能做出更好的反应一个缓慢的互联网连接将是AP preciated。

Any clues to how I can make responsiveness better on a slow internet connection will be appreciated.

推荐答案

要处理的一个方法是使用的线程池。我不知道是否有一个有限的限制,以同时运行的线程的数目,但创建和销毁它们是昂贵的。与线程池,则有可以执行任务的线程的数量有限。

One way to handle this is to use a thread pool. I don't know if there is a finite limit to the number of simultaneous threads, but creating and destroying them is expensive. With a thread pool, you have a limited number of threads that can perform tasks.

一旦完成一任务,这导致性能改进线程可以被重复使用。

A thread can be reused once it has finished a task, which leads to performance improvements.

如果你有更多的工作需要同时做比你的线程来执行它,你需要排队的工作,直到一个线程是免费的。

If you have more work that needs to be done simultaneously than you have threads to perform it, you need to queue up the work until a thread is free.