码迷,mamicode.com
首页 > 编程语言 > 详细

双线程互相等待

时间:2015-01-04 10:09:18      阅读:144      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!