首页 > 代码库 > 双线程互相等待
双线程互相等待
本代码是在查看Android ActivityManagerService的源代码时发现的一个现象,记录一下
AThread --> run() --> do Some thing --> notify main Thread --> wait
MainThread --> wait --> be notified and do some thing --> notify AThread
public static final Context main(int factoryTest) { AThread thr = new AThread(); thr.start(); synchronized (thr) { while (thr.mService == null) { try { thr.wait(); } catch (InterruptedException e) { } } } //do some thing ... ... synchronized (thr) { thr.mReady = true; thr.notifyAll();// notify AThread } return context; } // ActivityManagerService的内部类 static class AThread extends Thread { ActivityManagerService mService; Looper mLooper; boolean mReady = false; public AThread() { super("ActivityManager"); } @Override public void run() { Looper.prepare(); ... ... synchronized (this) { mService = m; mLooper = Looper.myLooper(); Watchdog.getInstance().addThread(new Handler(mLooper), getName()); notifyAll();// 通知 main thread } synchronized (this) { while (!mReady) { try { wait(); } catch (InterruptedException e) { } } } Looper.loop(); } }
双线程互相等待
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。