2017-05-24 35 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(); 
相關問題