android中和c++中生产者和消费者模式
16lz
2021-01-23
首先上代码,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;@Overrideprotected 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");elseLog.v("A","the token flag value is"+token.getFlag());btn.setOnClickListener(new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubWorkThread 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 {@Overridepublic 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 lk(img_mutex_); img_cv_.wait(lk,[this]{return this->isReady_;}); cv::Mat temp= img_.clone(); std::cout<<"grap picture,img size:"< 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"<
可以看到,两者基本是一样的,消费者首先要获得同步锁,然后wait(wait内部会释放同步锁),生产者这时候获得同步锁,生产数据,notify,释放同步锁(如果不释放,消费者是无法执行的),这时候消费者在wait处又可以开始执行了。
更多相关文章
- 线程池的封装和使用(二)
- Android studio 简单的多线程
- Android 为线程增加Looper
- Android中对后台任务线程性能的说明及优化
- Android 线程池管理工具类
- android:Handler开启线程定时循环
- Android 后台线程调用前台线程的几种方法
- Android 创建线程执行任务
- android 线程之创建一个子线程,并在UI线程中进行交互