我一直在測試android中的一些asynctasks。在AsyncTask中嵌套/正常for循環
但我發現有些不合邏輯的結果對這些代碼:
int a1Sum = 0;
int a2Sum = 0;
long a1Time = 0;
long a2Time = 0;
private class Async1 extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
a1Time = System.currentTimeMillis();
}
protected String doInBackground(Void... arg0) {
for (int i = 0; i < 10000; i++) {
publishProgress();
}
return "You are at PostExecute";
}
protected void onProgressUpdate(Void... arg0) {
a1Sum++;
}
protected void onPostExecute(String result) {
Log.d("A1 Time", String.valueOf(System.currentTimeMillis() - a1Time)); // records the executing time
AsyncTask async2 = new Async2().execute();
}
}
private class Async2 extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
a2Time = System.currentTimeMillis();
}
protected String doInBackground(Void... arg0) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 10; k++) {
for (int l = 0; l < 10; l++) {
publishProgress();
}
}
}
}
return "You are at PostExecute";
}
protected void onProgressUpdate(Void... arg0) {
a2Sum++;
}
protected void onPostExecute(String result) {
Log.d("A2 Time", String.valueOf(System.currentTimeMillis() - a2Time)); // records the executing time
}
}
這兩個asynctasks做同樣的工作,但這裏是不合邏輯的部分:
,你在代碼中看到,a1Time
和a2Time
記錄執行時間,這裏是他們的結果:
D/A1 Time: 1025
D/A2 Time: 768
D/A1 Time: 1022
D/A2 Time: 716
D/A1 Time: 1017
D/A2 Time: 729
D/A1 Time: 1063
D/A2 Time: 830
D/A1 Time: 1059
D/A2 Time: 784
我的問題是:是什麼讓Async2
跑得快嗎?
@ Kaushal28但不應該'Async1'更快,因爲它更簡單? –
有趣。現在轉身。讓線程1由線程2啓動。 – greenapps
如果'''''''''''''''''''''''''''''''''Async2''的實現和Aynsc1'完全相同,它會以相同的方式結束結果還是會有相同的執行時間?當代碼在主UI線程和後臺線程之間切換時會更好地剖析執行時間,這會增加開銷,因此需要跟蹤doInBackground()實現的時間。我認爲他們會以接近的執行時間結束。最後,(我可能要求太多,道歉),如果使用'executeOnExecutor(THREAD_POOL_EXECUTOR)''而不是''execute()''',它會一樣嗎? – ahasbini