0

我正在开发一个使用 JavaCameraView 类打开视频流并从中捕获帧的 Android 应用程序。然后,我的目标是实现一个工作线程,将这些帧保存到缓冲区中,另一个线程从缓冲区中获取每一帧,以便使用图像处理技术对其进行处理。所以缓冲区是这两个工作线程之间共享的资源,应该同时运行,因此同时填充和清空缓冲区。我想把缓冲区实现为一个ConcurrentLinkedQueue,两个线程都实现了Runnable接口。然后,在 Main Activity 中,我声明它们,实例化它们,然后启动它们,但似乎只有第一个开始运行,而第二个从未启动。我在这里发布我的代码:

1)缓冲区.java

public class Buffer {
private ConcurrentLinkedQueue<Mat> MyBuffer = new ConcurrentLinkedQueue<Mat>();
private static final String TAG = "MyBufferClass :: ";
private int index = 1;

public Buffer(){
    Log.d(TAG,"Buffer Created");
}

public void insertElementInTail(Mat element){
    MyBuffer.offer(element);
}

public Mat retrieveElementInHead(){
    synchronized (MyBuffer){
        if(!MyBuffer.isEmpty()){
            return MyBuffer.peek();
        }else{
            return null;
        }
    }
}

public Mat removeElementInHead(){
    synchronized (MyBuffer){
        if(!MyBuffer.isEmpty()){
            return MyBuffer.poll();
        }else{
            return null;
        }
    }
}

public int getSize(){
    return MyBuffer.size();
}
}

2)SaveInBuffer.java

public class SaveInBuffer implements Runnable {

private Handler myHandler;
private Buffer myBuffer;

public Handler myThreadHandler;
MainActivity mainActivity;
Handler mainHandler;
int what = -1;


public SaveInBuffer(Buffer myBuf, MainActivity mainActivity){
    //super("SaveInBuffer");
    this.myBuffer = myBuf;
    this.mainActivity = mainActivity;
    this.mainHandler = mainActivity.mainHandler;
}

@Override
public void run(){
    Looper.prepare();
    myThreadHandler = new Handler(){
        public void handleMessage( Message msg ){
             if(msg.what==4){
                 Mat returnedFrame = (Mat)msg.obj;
                 myBuffer.insertElementInTail(returnedFrame);
             }
        }
    };
    Looper.loop();
}

}

3)TakeFromBuffer.java

public class TakeFromBuffer implements Runnable{

public Handler consumerHandler;
private Buffer myBuffer;

public TakeFromBuffer(Buffer myBuffer){
    this.myBuffer = myBuffer;
}

@Override
public void run(){
    Looper.prepare();
    Mat consumedFrame = myBuffer.removeElementInHead();
    Looper.loop();
}
}

缓冲区在 MainActivity 中创建,然后作为参数传递给线程。问题是如何将 Buffer 作为共享资源进行管理,从而实现同步技术,以及如何同时启动两个线程,因为它们同时运行非常重要。

我该怎么办?任何帮助将不胜感激。

4

0 回答 0