所有 Android 应用都使用主线程来处理界面操作。在此主线程中调用长时间运行的操作可能会导致界面冻结和无响应。例如,如果您的应用从主线程发起网络请求,则应用的界面将冻结,直到收到网络响应。如果您使用 Java,可以创建额外的 后台线程 来处理长时间运行的操作,同时主线程继续处理界面更新。
本指南介绍了使用 Java 编程语言的开发者如何使用 线程池 在 Android 应用中设置和使用多个线程。本指南还介绍了如何定义要在线程上运行的代码,以及如何在其中一个线程与主线程之间进行通信。
并发库
了解线程的基本概念及其底层机制非常重要。但是,有许多流行库提供了这些概念之上的更高级抽象,以及用于在线程之间传递数据的现成实用程序。这些库包括适用于 Java 编程语言用户的 Guava 和 RxJava,以及我们为 Kotlin 用户推荐的 协程。
在实践中,您应该选择最适合您的应用和开发团队的库,尽管线程的规则保持不变。
示例概览
根据应用架构指南,本主题中的示例会发起网络请求,并将结果返回给主线程,然后应用可能会在屏幕上显示该结果。
具体来说,ViewModel
在主线程上调用数据层以触发网络请求。数据层负责将网络请求的执行移出主线程,并使用回调将结果发布回主线程。
为了将网络请求的执行移出主线程,我们需要在应用中创建其他线程。
创建多个线程
线程池 (thread pool) 是一个托管线程集合,可从队列中并行运行任务。新任务会在现有线程空闲时在其上执行。要将任务发送到线程池,请使用 ExecutorService
接口。请注意,ExecutorService
与 Android 应用组件 Service 无关。
创建线程开销很大,因此您应该只在应用初始化时创建一次线程池。请务必将 ExecutorService
实例保存在您的 Application
类中或 依赖注入容器 中。以下示例创建了一个包含四个线程的线程池,可用于运行后台任务。
public class MyApplication extends Application {
ExecutorService executorService = Executors.newFixedThreadPool(4);
}
您还可以根据预期工作负载配置线程池,方式有很多种。如需了解详情,请参阅配置线程池。
在后台线程中执行
在主线程上发起网络请求会导致线程等待(或称 阻塞),直到收到响应为止。由于线程被阻塞,操作系统无法调用 onDraw()
,您的应用会冻结,可能会导致出现应用无响应 (ANR) 对话框。因此,我们可以在后台线程上运行此操作。
发起请求
首先,我们来看看 LoginRepository
类,了解它是如何发起网络请求的
// Result.java
public abstract class Result<T> {
private Result() {}
public static final class Success<T> extends Result<T> {
public T data;
public Success(T data) {
this.data = data;
}
}
public static final class Error<T> extends Result<T> {
public Exception exception;
public Error(Exception exception) {
this.exception = exception;
}
}
}
// LoginRepository.java
public class LoginRepository {
private final String loginUrl = "https://example.com/login";
private final LoginResponseParser responseParser;
public LoginRepository(LoginResponseParser responseParser) {
this.responseParser = responseParser;
}
public Result<LoginResponse> makeLoginRequest(String jsonBody) {
try {
URL url = new URL(loginUrl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setDoOutput(true);
httpConnection.getOutputStream().write(jsonBody.getBytes("utf-8"));
LoginResponse loginResponse = responseParser.parse(httpConnection.getInputStream());
return new Result.Success<LoginResponse>(loginResponse);
} catch (Exception e) {
return new Result.Error<LoginResponse>(e);
}
}
}
makeLoginRequest()
是同步的,会阻塞调用线程。为了对网络请求的响应进行建模,我们有自己的 Result
类。
触发请求
当用户点击按钮时,ViewModel
会触发网络请求
public class LoginViewModel {
private final LoginRepository loginRepository;
public LoginViewModel(LoginRepository loginRepository) {
this.loginRepository = loginRepository;
}
public void makeLoginRequest(String username, String token) {
String jsonBody = "{ username: \"" + username + "\", token: \"" + token + "\" }";
loginRepository.makeLoginRequest(jsonBody);
}
}
在之前的代码中,LoginViewModel
在发起网络请求时会阻塞主线程。我们可以使用我们已实例化的线程池,将执行移至后台线程。
处理依赖注入
首先,遵循依赖注入原则,LoginRepository
接受 Executor 实例而不是 ExecutorService
,因为它是执行代码而不是管理线程
public class LoginRepository {
...
private final Executor executor;
public LoginRepository(LoginResponseParser responseParser, Executor executor) {
this.responseParser = responseParser;
this.executor = executor;
}
...
}
Executor 的 execute() 方法接受一个 Runnable。Runnable 是一种单一抽象方法 (SAM) 接口,其中包含一个在调用时在线程中执行的 run()
方法。
在后台执行
让我们创建另一个名为 makeLoginRequest()
的函数,该函数将执行移至后台线程,并暂时忽略响应
public class LoginRepository {
...
public void makeLoginRequest(final String jsonBody) {
executor.execute(new Runnable() {
@Override
public void run() {
Result<LoginResponse> ignoredResponse = makeSynchronousLoginRequest(jsonBody);
}
});
}
public Result<LoginResponse> makeSynchronousLoginRequest(String jsonBody) {
... // HttpURLConnection logic
}
...
}
在 execute()
方法中,我们创建了一个新的 Runnable
,其中包含我们要在后台线程中执行的代码块(在本例中为同步网络请求方法)。在内部,ExecutorService
会管理 Runnable
并在可用线程中执行它。
注意事项
应用中的任何线程都可以与其他线程并行运行,包括主线程,因此您应该确保代码是线程安全的。请注意,在我们的示例中,我们避免写入线程之间共享的变量,而是传递不可变数据。这是一种很好的做法,因为每个线程都使用自己的数据实例,从而避免了同步的复杂性。
如果需要在线程之间共享状态,则必须小心管理线程对状态的访问,使用锁等同步机制。这超出了本指南的范围。通常,您应该尽可能避免在线程之间共享可变状态。
与主线程通信
在上一步中,我们忽略了网络请求响应。要在屏幕上显示结果,LoginViewModel
需要知道结果。我们可以通过使用 回调 来实现这一点。
函数 makeLoginRequest()
应该将回调作为参数,以便它能异步返回值。网络请求完成或发生故障时,会调用包含结果的回调。在 Kotlin 中,我们可以使用高阶函数。但在 Java 中,我们必须创建新的回调接口才能实现相同的功能
interface RepositoryCallback<T> {
void onComplete(Result<T> result);
}
public class LoginRepository {
...
public void makeLoginRequest(
final String jsonBody,
final RepositoryCallback<LoginResponse> callback
) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
Result<LoginResponse> result = makeSynchronousLoginRequest(jsonBody);
callback.onComplete(result);
} catch (Exception e) {
Result<LoginResponse> errorResult = new Result.Error<>(e);
callback.onComplete(errorResult);
}
}
});
}
...
}
ViewModel
现在需要实现回调。它可以根据结果执行不同的逻辑
public class LoginViewModel {
...
public void makeLoginRequest(String username, String token) {
String jsonBody = "{ username: \"" + username + "\", token: \"" + token + "\" }";
loginRepository.makeLoginRequest(jsonBody, new RepositoryCallback<LoginResponse>() {
@Override
public void onComplete(Result<LoginResponse> result) {
if (result instanceof Result.Success) {
// Happy path
} else {
// Show error in UI
}
}
});
}
}
在此示例中,回调在调用线程(即后台线程)中执行。这意味着在切换回主线程之前,您无法直接修改或与界面层通信。
使用 Handler
您可以使用 Handler 将要在不同线程上执行的操作放入队列。要指定运行操作的线程,请使用该线程的 Looper 构造 Handler
。Looper 是一个为关联线程运行消息循环的对象。创建 Handler
后,您可以使用 post(Runnable) 方法在相应的线程中运行代码块。
Looper
包含一个辅助函数 getMainLooper(),用于检索主线程的 Looper
。您可以使用此 Looper
创建 Handler
,从而在主线程中运行代码。由于这是一种很常见的操作,您还可以将 Handler
的实例保存在与 ExecutorService
相同的位置
public class MyApplication extends Application {
ExecutorService executorService = Executors.newFixedThreadPool(4);
Handler mainThreadHandler = HandlerCompat.createAsync(Looper.getMainLooper());
}
将 Handler 注入到存储库中是一个很好的做法,因为它为您提供了更大的灵活性。例如,将来您可能希望传入一个不同的 Handler
以在单独的线程上调度任务。如果您总是与同一个线程通信,可以将 Handler
传递到存储库构造函数中,如以下示例所示。
public class LoginRepository {
...
private final Handler resultHandler;
public LoginRepository(LoginResponseParser responseParser, Executor executor,
Handler resultHandler) {
this.responseParser = responseParser;
this.executor = executor;
this.resultHandler = resultHandler;
}
public void makeLoginRequest(
final String jsonBody,
final RepositoryCallback<LoginResponse> callback
) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
Result<LoginResponse> result = makeSynchronousLoginRequest(jsonBody);
notifyResult(result, callback);
} catch (Exception e) {
Result<LoginResponse> errorResult = new Result.Error<>(e);
notifyResult(errorResult, callback);
}
}
});
}
private void notifyResult(
final Result<LoginResponse> result,
final RepositoryCallback<LoginResponse> callback,
) {
resultHandler.post(new Runnable() {
@Override
public void run() {
callback.onComplete(result);
}
});
}
...
}
或者,如果您想要更大的灵活性,可以将 Handler
传递给每个函数
public class LoginRepository {
...
public void makeLoginRequest(
final String jsonBody,
final RepositoryCallback<LoginResponse> callback,
final Handler resultHandler,
) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
Result<LoginResponse> result = makeSynchronousLoginRequest(jsonBody);
notifyResult(result, callback, resultHandler);
} catch (Exception e) {
Result<LoginResponse> errorResult = new Result.Error<>(e);
notifyResult(errorResult, callback, resultHandler);
}
}
});
}
private void notifyResult(
final Result<LoginResponse> result,
final RepositoryCallback<LoginResponse> callback,
final Handler resultHandler
) {
resultHandler.post(new Runnable() {
@Override
public void run() {
callback.onComplete(result);
}
});
}
}
在此示例中,传入存储库 makeLoginRequest
调用的回调在主线程上执行。这意味着您可以直接从回调中修改界面,或者使用 LiveData.setValue()
与界面通信。
配置线程池
您可以按照前面的示例代码所示,使用 Executor 辅助函数之一以及预定义设置来创建线程池。或者,如果您想自定义线程池的详细信息,可以直接使用 ThreadPoolExecutor 创建实例。您可以配置以下详细信息
- 初始池大小和最大池大小。
- 保持活跃时间 和时间单位。保持活跃时间是指线程在关闭之前可以保持空闲状态的最长持续时间。
- 一个保存
Runnable
任务的输入队列。此队列必须实现 BlockingQueue 接口。为了满足您的应用要求,您可以从可用的队列实现中进行选择。如需了解详情,请参阅 ThreadPoolExecutor 的类概览。
以下示例根据处理器核心总数、一秒的保持活跃时间和一个输入队列来指定线程池大小。
public class MyApplication extends Application {
/*
* Gets the number of available cores
* (not always the same as the maximum number of cores)
*/
private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// Instantiates the queue of Runnables as a LinkedBlockingQueue
private final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
// Sets the amount of time an idle thread waits before terminating
private static final int KEEP_ALIVE_TIME = 1;
// Sets the Time Unit to seconds
private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// Creates a thread pool manager
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
NUMBER_OF_CORES, // Initial pool size
NUMBER_OF_CORES, // Max pool size
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
workQueue
);
...
}