--- 怎么检查线程有耗时任务? --- #### 检测机制 1. WatchDog 2. BlockCanary #### WatchDog 1. 检查是否发生了死锁 2. 检查线程是否被任务 blocked ```java private void startOtherServices(){ final Watchdog watchdog = Watchdog.getInstance(); mActivityManagerService.systemReady(new Runnable(){ @Override public void run(){ Watchdog.getInstance().start(); } }) } public class Watchdog extends Thread{...} private Watchdog(){ super("watchdog"); mMinitorChecker = new HandlerChecker(FgThread.getHandler(), ...); mHandlerCheckers.add(mMinitorChecker); mHandlerCheckers.add(new HandlerCheck(new Handler(Looper.getMainLooper()), ...)); mHandlerCheckers.add(new HandlerChecker(UiThread.getHandler(), ...)); mHandlerCheckers.add(new HandlerChecker(IoThread.getHandler(), ...)); mHandlerCheckers.add(new HandlerChecker(DisplayThread.getHandler(), ...)); addMonitor(new BinderThreadMonitor()); } ``` ```java private static final class BinderThreadMonitor implements Watchdog.Monitor{ @Override public void monitor(){ Binder.blockUntilThreadAvailable(); } } void Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz){ return IPCThreadState::self()->blockUntilThreadAvailable(); } void IPCThreadState::blockUntilThreadAvailable(){ pthread_mutex_lock(&mProcess->mThreadCountLock); while(mProcess->mExecutingThreadsCount>=mProcess->mMaxThreads){ pthread_cond_wait(&mProcess->mThreadCountDecrement, &mProcess->mThreadCountLock); } pthread_mutext_unlock(&mProcess->mThreadCountLock); } status_t IPCThreadState::getAndExecuteCommand(){ talkWithDriver(); cmd = mIn.readInt32(); mProcess->mExecutingThreadsCount++; executeCommand(cmd); mProcess->mExecutingThreadsCount--; mpthread_cond_broadcast(&mProcess->mThreadCountDecrement); } ``` ```java // Watchdog#run public void run(){ while(true){ for(int i=0;i