ActivityManagerService中有这么两个方法,resetPriorityAfterLockedSection()和boostPriorityForLockedSection()。直接搜是看不到这两个方法在哪被调用的,这个涉及到ASM插桩,详细可以见:
Google教你用ASM:lockedregioncodeinjection
。
再此之前我们先理解一下什么叫优先级反转。
我们先假设三个任务准备执行,A,B,C,它们的优先级依次是A>B>C;
首先:C处于运行状态,获得CPU正在执行,同时占有了某种资源。
其次:A进入就绪状态,因为A优先级比C高,所以A获得CPU,A转为运行状态;C进入就绪状态;
第三:执行过程中需要使用资源,而这个资源又被等待中的C占有的,于是A进入阻塞状态,C回到运行状态;
第四:此时B进入就绪状态,因为优先级比C高,B获得CPU,进入运行状态;C又回到就绪状态;
此时,我们的B任务反而优先于A任务运行。
ASM解决优先级的方式:将线程优先级提高到UI优先级
我们可以先看AMS中代码:
private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
THREAD_PRIORITY_FOREGROUND:Standard priority of threads that are currently running a user interface that the user is interacting with. Applications can not normally change to this priority; the system will automatically adjust your application threads as the user moves through the UI.
大意就是这是UI线程的标准优先级,当用户进行在操作UI时,系统会自动调整APP到此优先级。
接下来我们看调整优先级的方法:
839 static void boostPriorityForLockedSecti