【Android面试】2023最新面试专题十一:Java并发编程
26 AsyncTask的原理
这道题想考察什么?
是否了解AsyncTask的原理与真实场景使用,是否熟悉AsyncTask的原理
考察的知识点
AsyncTask的原理的概念在项目中使用与基本知识
考生应该如何回答
AsyncTask是Android给我们提供的一个轻量级的用于处理异步任务的类。
构造函数
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
初始化了两个变量,mWorker和mFuture,并在初始化mFuture的时候将mWorker作为参数传入。mWorker是一个Callable对象,mFuture是一个FutureTask对象,这两个变量会暂时保存在内存中,稍后才会用到它们。 FutureTask实现了Runnable接口。
mWorker中的call()方法执行了耗时操作,即result = doInBackground(mParams);
,然后把执行得到的结果通过postResult(result);
,传递给内部的Handler跳转到主线程中。在这里这是实例化了两个变量,并没有开启执行任务。
execute方法
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
execute
方法调用了executeOnExecutor
方法并传递参数sDefaultExecutor和params。
再看executeOnExecutor
方法:
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
//判断当前状态
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
//将状态置为运行态
mStatus = Status.RUNNING;
//主线程中最先调用onPreExecute方法,进行准备工作
onPreExecute();
//将参数传给mWorker
mWorker.mParams = params;
//调用线程池,执行任务
exec.execute(mFuture);
return this;
}
executeOnExecutor
方法首先判断状态,若处于可执行态,则将状态置为RUNNING。然后调用了onPreExecute
方法,交给用户进行执行任务前的准备工作。核心部分在于 exec.execute(mFuture)
。exec即sDefaultExecutor。
线程池
查看sDefaultExecutor定义:
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
再看一下SerialExecutor类
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
sDefaultExecutor是一个串行线程池,作用在于任务的排队执行。
从SerialExecutor的源码可以看出,mFuture是插入到mTasks任务队列的对象。当mTasks中没有正在活动的AsyncTask任务,则调用scheduleNext
方法执行下一个任务。若一个AsyncTask任务执行完毕,则继续执行下一个AsyncTask任务,直至所有任务执行完毕。通过分析可以发现真正去执行后台任务的是线程池THREAD_POOL_EXECUTOR。
在这个方法中,有两个主要步骤。
- 向队列中加入一个新的任务,即之前实例化后的mFuture对象。
- 调用
scheduleNext()
方法,调用THREAD_POOL_EXECUTOR执行队列头部的任务。
THREAD_POOL_EXECUTOR定义如下:
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
实际是个线程池,开启了一定数量的核心线程和工作线程。然后调用线程池的execute()方法。执行具体的耗时任务,即开头构造函数中mWorker中call()方法的内容。先执行完doInBackground()方法,又执行postResult()方法,下面看该方法的具体内容:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
该方法向Handler对象发送了一个消息,下面具体看AsyncTask中实例化的Hanlder对象—InternalHandler的源码:
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
InternalHandler接收到MESSAGE_POST_RESULT时调用result.mTask.finish(result.mData[0])
;即执行完了doInBackground()方法并传递结果,那么就调用finish()方法。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
finish
方法中若任务没有取消则调用onPostExecute
方法发送结果,若任务取消则调用onCancelled
方法。finish方法是在主线程中执行的。
InternalHandler是一个静态类,为了能够将执行环境切换到主线程,因此这个类必须在主线程中进行加载。所以变相要求AsyncTask的类必须在主线程中进行加载。
通过上述流程已经顺序找到了onPreExecute
、doInBackground
、onPostExecute
方法,那么onProgressUpdate
是如何执行的呢?
首先查看 publishProgress
方法:
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
在doInBackground
中调用publishProgress
方法,publishProgress
方法发送MESSAGE_POST_PROGRESS消息和进度values,InternalHandler在接收到MESSAGE_POST_PROGRESS消息中调用onProgressUpdate
方法。因此onProgressUpdate
也是在主线程中调用。
小结
通过上述一步步的源码分析过程,已经掌握了AsyncTask任务的执行过程。AsyncTask中有两个线程池串行线程池sDefaultExecutor和线程池THREAD_POOL_EXECUTOR。sDefaultExecutor用于任务的排队,THREAD_POOL_EXECUTOR真正的执行任务。线程的切换使用Handler(InternalHandler)实现。
27 AsyncTask中的任务是串行的还是并行的?
这道题想考察什么?
是否了解AsyncTask中的任务是串行的还是并行的与真实场景使用,是否熟悉AsyncTask中的任务是串行的还是并行的
考察的知识点
AsyncTask中的任务是串行的还是并行的概念在项目中使用与基本知识
考生应该如何回答
AsyncTask中的任务在4.0以上是串行执行的,在AsyncTask
中提交的任务默认都会通过:SerialExecutor线程池执行:
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();//当本次执行完之后,才会调用下一个执行
}
}
});
if (mActive == null) {//如果一个正在执行的都没有,那么就启动执行
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);//将任务添加到线程池
}
}
}
通过上面的源码可以发现,每次执行完一个任务后,才会调用scheduleNext往线程池里面添加任务,所以即使线程池是并行的,但是我添加任务的时候是串行的,所以api22中的asynctask是串行的,那么线程池其实再多的线程也没用了,反正每次都只有一个任务在里面。
另外,在AsyncTask中还存在一个executeOnExecutor(Executor exec, Params... params)
方法,能够指定线程池。所以非默认情况下,AsyncTask也能够并行执行任务。
28 Android中操作多线程的方式有哪些?
这道题想考察什么?
是否了解Android中操作多线程的方式有哪些与真实场景使用,是否熟悉Android中操作多线程在工作中的表现是什么?
考察的知识点
Android中操作多线程的方式有哪些的概念在项目中使用与基本知识
考生应该如何回答
常见的实现多线程的手段有五种:
第一种:Thread,Runnable
第二种:HandlerThread
第三种:AsyncTask
第四种:Executor
第五种:IntentService
Thread与Runnable
Android中创建线程最基本的两种方法,使用Thread类或Runnable接口:
此方式是线程最基础的用法,一般用于界面上比较简单的快捷用法,在Android中一般跟Handler一起使用,用于线程中的通信。那Android中为了方便这种通信方式,就生成了一个HandlerThread类,将Thread和Handler结合起来方便了使用。
/**
* 继承Thread
*/
public class NewThread extends Thread{
@Override
public void run() {
super.run();
}
}
/**
* 实现Runnable接口
*/
public class NewThread2 implements Runnable{
@Override
public void run() {
}
}
HandlerThread
HandlerThread本质上就是一个Thread,完成了对Thread与Handler的结合。主要解决的问题是,在一个已经运行的线程中去执行一些任务。
官方解释是:
Thread. Handy class for starting a new thread that has a looper.
The looper can then be used to create handler classes.
下面代码中:HandlerThread在运行中,可以通过handler进行一些任务处理。
它的原理其实就是在HandlerThread线程内部有一个Looper变量,进行loop()的死循环,然后通过MessageQueue进行一系列任务的排队和处理。
有开发者会想,这不就是普通的Thread+Looper+Handler吗,其实差不太多,HandlerThread就相当于系统帮你封装了一个带looper对象的线程,不需要你自己去手动操作Looper
那么这个HandlerThread到底有什么实际应用呢?
一般用于Android中需要新建子线程进行多个任务处理,并且需要和主线程通信。后面要说的IntentService 内部其实就是用了HandlerThread实现的。(其实我个人在实际项目中用的很少,一般用Executors.newSingleThreadExecutor()方法代替,一样的线程中管理任务队列,后面会详细说到线程池)
HandlerThread mHandlerThread=new HandlerThread("");
mHandlerThread.start();
Handler mHandler =new Handler(mHandlerThread.getLooper()){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
}
};
mHandler.sendEmptyMessage(0);
AsyncTask
AsyncTask是轻量级的异步任务类,可以在线程池中执行后台任务,然后把执行的进度和最终结果传递给主线程用于更新UI。
如果需要新建线程进行多个任务排队串行执行并且完成和主线程通信,可以使用HandlerThread。那么如果是单一任务呢,简单的任务呢?
比如我就需要请求一个接口,然后进行UI更新,那么就可以用到AsyncTask,它的优点在于简单快捷,过程可控。
new AsyncTask<Void, Void, String>() {
@Override
protected void onPreExecute() {
//请求接口之前,初始化操作
super.onPreExecute();
}
@Override
protected String doInBackground(Void... parameters) {
//请求接口
return "";
}
@Override
protected void onProgressUpdate(Void... values) {
//在主线程显示线程任务执行的进度
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String responseString) {
//接收线程任务执行结果
}
}.execute();
Executor
Executor即线程池,可以管理多个线程并行执行,线程池的优点就在于可以线程复用,并且合理管理所有线程。线程池具体使用与实现:《4.22 线程池有几种实现方式,线程池的七大参数有哪些?》
IntentService
IntentService是一个Service,自带工作线程,并且线程任务结束后自动销毁的一个类。IntentService其实封装了HandlerThread,同时又具备Service的特性。其中onHandleIntent方法即为异步执行的方法:
@Override
public void onCreate() {
super.onCreate();
//创建新线程并start
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
//创建新线程对应的handler
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
//service启动后发送消息给handler
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
//handler收到消息后调用onHandleIntent方法
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
29 Android开发中怎样判断当前线程是否是主线程 (字节跳动)
这道题想考察什么?
是否了解怎样获取当前线程是否是主线程有哪些与真实场景使用,是否熟悉怎样获取当前线程是否是主线程在工作中的表现是什么?
考察的知识点
怎样获取当前线程是否是主线程的概念在项目中使用与基本知识
考生应该如何回答
Android开发中, 有时需要判断当前线程到底是主线程, 还是子线程, 例如: 我们在自定义View时, 想要让View重绘, 需要先判断当前线程到底是不是主线程, 然后根据判断结果来决定到底是调用 invalidate()
还是 postInvalidate()
方法。
在工作中获取当前的主线程,主要是借助Android中的Looper:
Looper.getMainLooper() == Looper.myLooper();
Looper.getMainLooper().getThread() == Thread.currentThread();
Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
30 线程间如何通信?
这道题想考察什么?
是否了解线程间如何通信与真实场景使用,是否熟悉线程间如何通信该如何操作的本质区别?
考察的知识点
Handler
考生应该如何回答
线程之间进行通信的方式需要基于具体需求分析,如果仅仅只是为了完成线程间的同步,使用锁如synchronized 即可;如果需要完成线程之间的协作,也可以采用wait/notify、CountDownLatch或者Cyclicbarrier等方式。而在Android中还设计了Handler机制可以完成线程间通信。
Handler是Android系统中线程间传递消息的一种机制。
最后
整理不易,关注哇哇,以上均可分享哦~