首页 > 编程语言 > 详细

双线程互相等待

时间:2015-01-04 10:06:32      阅读:173      评论:0      收藏:0      [点我收藏+]

本代码是在查看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();
        }
    }


双线程互相等待

原文:http://blog.csdn.net/limingxiao117/article/details/42372731

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!