首先上代码,android
package com.wmz.helloworld;
import java.util.Random;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Demo extends android.app.Activity {
private class Token {
private String flag;
public Token() {
setFlag(null);
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getFlag() {
return flag;
}
}
private Token token = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
Button btn = (Button) findViewById(R.id.button1);
token = new Token();
if(token.getFlag() ==null)
Log.v("A","the token flag value is null");
else
Log.v("A","the token flag value is"+token.getFlag());
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
WorkThread workthread = new WorkThread();
workthread.start();
Random r=new Random();
for (int i = 0;i<10; i++) {
try {
Thread.sleep((r.nextInt(9)+1)*1000); //增加不确定性,至少睡眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (token) {
token.setFlag("wangmz"+Integer.toString(i));
token.notifyAll();
Log.v("Main",Integer.toString(i));
}
}
}
});
}
private class WorkThread extends Thread {
@Override
public void run() {
Random r=new Random();
while (true) {
// try {
// Thread.sleep((r.nextInt()+1)*1000);//可能在sleep的时候其他线程执行notify()。但此时对这个线程不起作用。所以结果不会按顺序出现
// } catch (InterruptedException e1) {
// e1.printStackTrace();
// }
synchronized (token) {
try {
token.wait();
Log.v("Main", "the value is " + token.getFlag());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.v("work","while!!");
}
}
}
}
c++中实现
std::mutex img_mutex_;
std::condition_variable img_cv_;
cv::Mat camera::grapPicture()
{
std::unique_lock<std::mutex> lk(img_mutex_);
img_cv_.wait(lk,[this]{return this->isReady_;});
cv::Mat temp= img_.clone();
std::cout<<"grap picture,img size:"<<temp.rows<<","<<temp.cols<<std::endl;
isReady_=false;
return temp;
}
void camera::work_loop()
{
while(isRunning)
{
{
std::lock_guard<std::mutex> lk(img_mutex_);
(*capture_)>>img_;
isReady_=true;
}
img_cv_.notify_one();
if(onpreviewcb_)
onpreviewcb_(img_);
//if here don't sleep,this thread will lock img_mutex_ in all most time,and grapPicture will have not chance to grap image
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
std::cout<<"camera:work_loop end"<<std::endl;
}
可以看到,两者基本是一样的,消费者首先要获得同步锁,然后wait(wait内部会释放同步锁),生产者这时候获得同步锁,生产数据,notify,释放同步锁(如果不释放,消费者是无法执行的),这时候消费者在wait处又可以开始执行了。