Create 检查线程耗时任务.md

master
Omooo 5 years ago
parent 10429c85af
commit d066d53e48
  1. 97
      blogs/Android/Framework/Interview/技巧心得相关/检查线程耗时任务.md

@ -0,0 +1,97 @@
---
怎么检查线程有耗时任务?
---
#### 检测机制
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<mHandlerCheckers.size();i++){
HandlerChecker hc = mHandlerCheckers.get(i);
hc.scheduleCheckLocked();
}
}
}
public void scheduleCheckLocked(){
if(mMonitors.size()==0&&mHandler.getLooper().getQueue().isPolling()){
mCompleted = true;
return;
}
if(!mCompleted){
return;
}
mCompleted = false;
mCurrentMonitor = null;
mStartTime = SystemClock.uptimeMillis();
mHandler.postAtFromOfQueue(this);
}
```
```java
public ActivityManagerService(Context systemContext){
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
```
Loading…
Cancel
Save