我正在尝试创建一个运行应用程序属性的应用程序,例如(进程名称,图标,内存等),并在listview中显示它们。
由于我在主线程中执行它们需要花费太多时间。 如何在此示例循环中创建更多线程? (我是android编程的新手)
//would like to run this loop in parallel
for (int i = 0; i < processes.size(); i++) {
// calculations
}
答案 0 :(得分:0)
尝试使用多个AsyncTasks并使用task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
执行任务或使用多个线程并行处理。
<强>的AsyncTask 强>
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
//would like to run this loop in parallel
//You can also start threads
for (int i = 0; i < processes.size(); i++) {
// calculations
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
使用主题
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < processes.size() /2; i++) {
// calculations
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = processes.size() /2; i < processes.size(); i++) {
// calculations
}
}
});
thread1.start();
thread1.start();
答案 1 :(得分:0)
Hi I think you have one loop to iterate which is the data got from any Web Service.
- Basically all the long running process which are need for UI changes can be run inside the AsyncTask, which will create background threads.
class AsyncExaple extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
//What ever the long running tasks are run inside this block
//would like to run this loop in parallel
for (int i = 0; i < processes.size(); i++) {
// calculations
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
};
To call this AsyncTask do as follows
AsyncExaple asyncExaple = new AsyncExaple();
asyncExaple.execute();
If you still want to use the Threads use below code:
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();