android中运用CountDownLatch

以下场景,一个thread等待UI线程更新状态后才可以使用

public class CountDown extends Activity{
    private CountDownLatch mCountDownLatch;
    private static final int GET_TEST_MSG=100;
    private boolean mTestFlag=false;

    final Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_TEST_MSG:
                    mTestFlag=true;
                    mCountDownLatch.countDown();
                    break;
            }

        }
    };

    private void testThread(){
        mTestFlag=false;
        new Thread(new Runnable() {
            @Override
            public void run() {
                mCountDownLatch=new CountDownLatch(1);
                mHandler.sendMessage(mHandler.obtainMessage(GET_TEST_MSG));

                try{
                    mCountDownLatch.await();

                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

 

posted @ 2017-09-25 11:06  我在途中  阅读(2334)  评论(0编辑  收藏  举报