线程之间除了同步互斥,还要考虑通信。
在Java5之前我们的通信方式为:wait 和 notify。那么Condition的优势是支持多路等待,就是我可以定义多个Condition,每个condition控制线程的一条执行通路。传统方式只能是一路等待。
Demo实例
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class AwaitDemo extends Activity {
protected String tag = "AwaitDemo";
private Button button1;
private TextView text;
protected boolean flag = false;
private int count = 0;
private Handler handler = new Handler();
private final Lock lock = new ReentrantLock();
private final Condition sign = lock.newCondition();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
text = (TextView) findViewById(R.id.text);
text.setText("");
startWaittingThread();
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flag = true;
lock.lock();
sign.signal();// 激活信号
lock.unlock();
}
});
}
private void startWaittingThread() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
Log.i(tag,"#Lock");
lock.lock();
if (!flag) {// 阻塞条件
try {
sign.await();// 等待信号
flag = false;
} catch (InterruptedException e) {
// ##
}
}
lock.unlock();
setText(count++);
}
}
}).start();
}
protected void setText(final int num) {
handler.post(new Runnable() {
@Override
public void run() {
text.append("#" + num + "\n");
}
});
}
}
每一次点击,都会发出信号通知线程执行。
Demo运行效果
相关的API说明如下
signal()函数:Wakes up one waiting thread.
await()函数:
Causes the current thread to wait until it is signalled or interrupted. 这个线程锁定通常还用在take()和put()中,往后再总结。
Demo中还涉及到Java的ReentrantLock机制。
ReentrantLock和synchronized两种锁定机制需要进一步分析。
参考
http://wangpengfei360.iteye.com/blog/1423273
本文来自CSDN博客 转载请联系作者并且标明出处http://blog.csdn.net/dreamintheworld/article/details/38846667