Android 中的线程数组
我正在寻找使用Java(Android)中的多线程构建一个应用程序,就像这样(注意,这不是我的想法,而且很可能充满错误)
thread [] jobs
int threadCounter
// Some code
job = new Runnabul(){
// Do something intresting
}
// Some more code
while(true){
jobs[threadCounter] = new job();
threadCounter++;
}
这在某些时候会导致手机内存不足,并且死了,所以对于我的问题,我怎么知道我什么时候接近耗尽资源(这样我就可以减慢新线程的创建速度)?
谢谢
I'm looking to build an application useing mutipul threads in Java (Android) something like this (n.b. this is off the top of my head and most likely riddled with errors)
thread [] jobs
int threadCounter
// Some code
job = new Runnabul(){
// Do something intresting
}
// Some more code
while(true){
jobs[threadCounter] = new job();
threadCounter++;
}
This will at some point cause the phone to run out of memory and die, so to my questron, how do I know when I'm close to running out of resorces (and so I can slow the creation of new threads)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好使用执行器服务,如此处和此处。创建一个线程池,然后只传递一个 Runnable (要执行的任务)。
正如 derekerdmann 所说,如果你真的想做线程数组,请使用 ASyncTask。如果内存不足,系统会注意停止它们,并且您可以比线程更轻松地管理它们。
It's better to use the executor service, as described here and here. Create a pool of thread, and then just pass a Runnable (a task to execute).
As derekerdmann say, if you really want to do an array of thread, use ASyncTask. The system will take care to stop them in case of low memory, and you can manage them more easily than thread.
您应该考虑使用 Android 的 AsyncTask 而不是您自己的线程。它们使用 java.util.concurrent 中的 Java 执行器,因此操作系统完全自行管理线程创建和系统资源。
AsyncTasks 还具有用于在 UI 线程上发布进度和更新 GUI 的有用方法。
You should look into using Android's AsyncTask instead of your own threads. They use Java's executors from java.util.concurrent, so the OS manages thread creation and system resources completely on its own.
AsyncTasks also have useful methods for publishing progress and updating the GUI on the UI thread.