2017-05-24 76 views
0

我试图让一个应用程序运行应用程序属性,如(进程名称,图标,内存等),并在列表视图中显示它们。如何减少使用线程的android应用程序加载时间?

因为我在主线程中执行它们,所以花费的时间太多。 如何在此示例循环中创建更多线程? (我是新来的Android编程)

//would like to run this loop in parallel 
for (int i = 0; i < processes.size(); i++) { 
// calculations 
} 

回答

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(); 
+0

感谢您的回复..我想您的两个方法,但它并不显示的AsyncTask和崩溃名单在线程中。 –

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(); 
相关问题