Android编程知识
Android 使用 ExecutorService和Future搭配使用
2025-01-27 35 0
简介 Android 使用 ExecutorService和Future搭配使用
直接上示例代码
Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// 执行耗时任务
System.out.println("============9in sub");
// 在子线程中初始化 Looper
Looper.prepare();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// 3秒后执行的代码
// 例如:Toast.makeText(getApplicationContext(), "延时3秒后执行", Toast.LENGTH_SHORT).show();
System.out.println("end time");
Looper.myLooper().quit();
}
}, 15000); // 参数是毫秒,所以3000毫秒 = 3秒
/// 写在Looper.loop()之后的代码不会被立即执行,当调用后mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行
// 循环结束后,销毁 Looper
Looper.loop();
System.out.println("============9in sub88888888");
return "abc";
}
});
executor.shutdown(); // 不要忘记关闭ExecutorService
try {
String result = future.get(5, TimeUnit.SECONDS); // 设置超时时间
System.out.println("result=" + result);
// 处理结果或更新UI在主线程中处理
} catch (Exception B) {
future.cancel(true);
MessageBox.Show(getContext(), B.toString());// 获取异常的描述信息,这通常是第一行信息
}