作者:手机用户2502938443 | 来源:互联网 | 2023-09-23 11:46
首先上代码,androidpackagecom.wmz.helloworld;importjava.util.Random;importandroid.os.B
首先上代码,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 &#61; flag;}public String getFlag() {return flag;}}private Token token &#61; null;&#64;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.demo);Button btn &#61; (Button) findViewById(R.id.button1);token &#61; new Token();if(token.getFlag() &#61;&#61;null)Log.v("A","the token flag value is null");elseLog.v("A","the token flag value is"&#43;token.getFlag());btn.setOnClickListener(new OnClickListener() { public void onClick(View v) {// TODO Auto-generated method stubWorkThread workthread &#61; new WorkThread();workthread.start(); Random r&#61;new Random();for (int i &#61; 0;i<10; i&#43;&#43;) {try { Thread.sleep((r.nextInt(9)&#43;1)*1000); //增加不确定性,至少睡眠1秒} catch (InterruptedException e) {e.printStackTrace();}synchronized (token) {token.setFlag("wangmz"&#43;Integer.toString(i));token.notifyAll();Log.v("Main",Integer.toString(i));} }}}); }private class WorkThread extends Thread {&#64;Overridepublic void run() {Random r&#61;new Random();while (true) {
// try {
// Thread.sleep((r.nextInt()&#43;1)*1000);//可能在sleep的时候其他线程执行notify()。但此时对这个线程不起作用。所以结果不会按顺序出现
// } catch (InterruptedException e1) {
// e1.printStackTrace();
// }synchronized (token) {try {token.wait();Log.v("Main", "the value is " &#43; token.getFlag());} catch (InterruptedException e) {e.printStackTrace();}}Log.v("work","while!!");}}}
}
c&#43;&#43;中实现
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&#61; img_.clone();std::cout<<"grap picture,img size:"<}void camera::work_loop()
{while(isRunning){{std::lock_guard lk(img_mutex_);(*capture_)>>img_;isReady_&#61;true;}img_cv_.notify_one();if(onpreviewcb_)onpreviewcb_(img_);//if here don&#39;t sleep,this thread will lock img_mutex_ in all most time,and grapPicture will have not chance to grap imagestd::this_thread::sleep_for(std::chrono::milliseconds(10));}std::cout<<"camera:work_loop end"<}
可以看到&#xff0c;两者基本是一样的&#xff0c;消费者首先要获得同步锁&#xff0c;然后wait&#xff08;wait内部会释放同步锁&#xff09;&#xff0c;生产者这时候获得同步锁&#xff0c;生产数据&#xff0c;notify&#xff0c;释放同步锁&#xff08;如果不释放&#xff0c;消费者是无法执行的&#xff09;&#xff0c;这时候消费者在wait处又可以开始执行了。