线程操作经常用到wait和notify,用起来稍显繁琐,而Android给我们封装好了一个ConditionVariable类,用于线程同步。提供了三个方法block()、open()、close()。
void block() //阻塞当前线程,直到条件为open void 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();
本文转自我爱物联网博客园博客,原文链接:http://www.cnblogs.com/yydcdut/p/4273526.html,如需转载请自行联系原作者