Android之ConditionVariable使用
2021-06-29 本文已影响0人
Lee_5566
image.png
ConditionVariable
Android开发中,需要线程同步,可以使用Java系统库的wait()和notify()。
但是这些代码的编写比较麻烦,Android提供了一个ConditionVariable类方便线程同步操作。
ConditionVariable有三个方法:
- block()
void block()
阻塞当前线程,直到条件为open
void block(long timeout)
阻塞当前线程,直到条件为open或超时 - open()
释放所有阻塞的线程 - close()
将条件重置为close
ConditionVariable 在创建时还有一种构造方法是 public ConditionVariable (boolean state) ,如果为true,默认时为opened,如果为false则是closed. ,默认public ConditionVariable()为closed.
使用实例
public class MainActivity extends Activity implements OnClickListener {
private Button btn_output;
private TextView textView;
private MyHandler mHandler;
private boolean isStart;
private String str = "";
private ConditionVariable mConditionVariable;
private final int REFRESHTEXT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取按钮
btn_output = (Button) findViewById(R.id.btn);
btn_output.setOnClickListener(this);
textView = (TextView) findViewById(R.id.txt);
mHandler = new MyHandler();
mConditionVariable = new ConditionVariable();
isStart = true;
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(isStart) {
//延时等待3秒
mConditionVariable.block(3000);
//如果是点击了按钮,则先将条件重置,否则block会失效
mConditionVariable.close();
//线程唤醒后通知主线程更新TextView的文本
mHandler.sendEmptyMessage(REFRESHTEXT);
}
}
}).start();
}
private class MyHandler extends Handler {
public void handleMessage(Message msg) {
switch(msg.what) {
case REFRESHTEXT:
textView.setText(str += 's');
break;
}
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mConditionVariable.open();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
isStart = false;
}
}