我正在尝试使用 AsyncTask 使任务与主线程分开运行,从而防止在任务运行时锁定线程。我是否误解了 AsyncTask 的用途?
主线程调用代码:
public void onClick(View view) {
int input = Integer.parseInt(editInput.getText().toString());
String out = "";
try {
out = new RunAsyncTask().execute(Integer.toString(input)).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
从 AsyncTask 类:
protected String doInBackground(String... params) {
long start, stop;
long result;
String out = "";
int input = Integer.parseInt(params[0]);
// Dalvik (Java) - Recursive:
start = System.currentTimeMillis();
result = FibLib.fibJR(input);
stop = System.currentTimeMillis();
out += String.format("Dalvik (Java) recursive: %d (%d msec)", result, stop - start);
// Dalvik (Java) - Iterative:
start = System.currentTimeMillis();
result = FibLib.fibJI(input);
stop = System.currentTimeMillis();
out += String.format("\nDalvik (Java) iterative: %d (%d msec)", result, stop - start);
return out
从 FibLib 类(由 AsyncTask 调用):
public class FibLib {
public static long fibJR(long n) { //
if (n <= 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fibJR(n - 1) + fibJR(n - 2);
}
// Java implementation - iterative:
public static long fibJI(long n) { //
long previous = -1;
long result = 1;
for (long i = 0; i <= n; i++) {
long sum = result + previous;
previous = result;
result = sum;
}
return result;
}
然而,当运行它时,如果任务不仅仅是一个小而快的任务,主 GUI 线程仍然被锁定并崩溃。我在这里有什么误解?