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
- android ConditionVariable
- Android ConditionVariable
- Android ConditionVariable的用法
- ConditionVariable
- Android 线程同步 ConditionVariable的用法
- ConditionVariable在Android应用开发中的用法
- Android 并发二三事之利用CountDownLatch 或 ConditionVariable实现自定义Future
- ConditionVariable的用法
- 线程 同步 ConditionVariable
- ConditionVariable的用法
- ConditionVariable的用法
- ConditionVariable的用法
- ConditionVariable的用法
- ConditionVariable的用法
- ConditionVariable的用法
- 方便的ConditionVariable
- ConditionVariable的用法 .
- Conditionvariable的用法
- vertx学习成果
- iOS开源项目推荐|侧滑与右滑返回手势;几句代码快速集成自定义转场效果+ 全手势驱动
- 解决 "X: user not authorized to run the X server, aborting."
- 前端框架之SiteMesh
- Linux 解除安裝 Java?
- Android ConditionVariable
- 加密会话(SSL)Cookie 中缺少 Secure 属性
- Java基础——初始化块
- firefox profile问题的排查
- self和Super的msgSend
- 仿饿了么百度地图定位
- POJ1006 Biorhythms (CRT)
- 32位与64位下各类型长度对比
- Linux syslog机制