Android ConditionVariable

来源:互联网 发布:影视包装培训软件 编辑:程序博客网 时间:2024/05/22 15:09

Android -- ConditionVariable


obj.wait()  obj.notify() 的方式   notify先调, wait 会一直等待

线程操作经常用到wait和notify,用起来稍显繁琐,而Android给我们封装好了一个ConditionVariable类,用于线程同步。提供了三个方法block()、open()、close()。

复制代码
void block()//阻塞当前线程,直到条件为openvoid block(long timeout)//阻塞当前线程,直到条件为open或超时void open()//释放所有阻塞的线程void close()//将条件重置为close
复制代码

ConditionVariable 在创建时还有一种构造方法是 public ConditionVariable (boolean state) ,如果为true,默认时为opened,如果为false则是closed. ,默认public ConditionVariable()为closed.

源码

其实很好理解

private volatile boolean mCondition;

成员内部变量。

//默认构造函数 public ConditionVariable(){        mCondition = false;}
public ConditionVariable(boolean state){        mCondition = state;}

open,释放阻塞,即notifyAll一下,此时成员变量变为true。

复制代码
public void open(){         synchronized (this) {             boolean old = mCondition;             mCondition = true;             if (!old) {                 this.notifyAll();             }         }}
复制代码

close,重置成员变量为false

public void close(){         synchronized (this) {             mCondition = false;         }}

block,只有在成员变量为false的时候进行wait等待

复制代码
public void block(){         synchronized (this) {             while (!mCondition) {                 try {                     this.wait();                 }                 catch (InterruptedException e) {                }            }        }}
复制代码
复制代码
public boolean block(long timeout){       // Object.wait(0) means wait forever, to mimic this, we just        // call the other block() method in that case.  It simplifies        // this code for the common case.        if (timeout != 0) {            synchronized (this) {                long now = System.currentTimeMillis();                long end = now + timeout;                while (!mCondition && now < end) {                    try {                        this.wait(end-now);                    }                    catch (InterruptedException e) {                    }                    now = System.currentTimeMillis();                }                return mCondition;            }        } else {            this.block();            return true;        }}
复制代码

code

简单的延时:

复制代码
new Thread(new Runnable() {            @Override            public void run() {                // TODO Auto-generated method stub                while(isStart) {                    //延时等待3秒                    mConditionVariable.block(3000);                    //将条件重置,否则block会失效                    mConditionVariable.close();                    //线程唤醒后通知主线程
                    mHandler.sendEmptyMessage(REFRESHTEXT);                }            }        }).start();
复制代码
0 0
原创粉丝点击