Android and android Official Website
Thread operations often use wait and policy, which are a little tedious to use. Android encapsulates a ConditionVariable class for thread synchronization. Three methods are provided: block (), open (), and close ().
Void block () // block the current thread until the condition is openvoid block (long timeout) // block the current thread until the condition is open or the void open () times out () // release all blocked threads void close () // reset the condition to close
ConditionVariable also has a public constructor when it is created.ConditionVariable (boolean state)If it is true, the default value is opened. If it is false, it is closed. The default value is public ConditionVariable.
Source code
Actually, it is easy to understand
private volatile boolean mCondition;
Member internal variables.
// Default constructor public ConditionVariable () {mCondition = false ;}
public ConditionVariable(boolean state){ mCondition = state;}
Open, release blocking, that is, when policyall is clicked, the member variable becomes true.
public void open(){ synchronized (this) { boolean old = mCondition; mCondition = true; if (!old) { this.notifyAll(); } }}
Close, reset the member variable to false
public void close(){ synchronized (this) { mCondition = false; }}
Block. wait waits only when the member variable is false.
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
Simple latency:
New Thread (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub while (isStart) {// wait for 3 seconds for mConditionVariable latency. block (3000); // reset the condition. Otherwise, the block will become invalid. close (); // notify the main thread after the thread wakes up
mHandler.sendEmptyMessage(REFRESHTEXT); } } }).start();
I am the dividing line of tiantiao