How to make threads work in Series

不问归期 提交于 2019-12-24 17:27:28

问题


I have created a CameraApp. And getting byte[] cameraPreviewCallback in onPreviewFrame(byte byteArray[] , Camera camera)

I am converting these byteArray to rgb and doing a lot of stuff too. So It is working slowly. So I think I should get benefit from java.util.concurrent package. But didn't find an easy way to handle what I want.

I want multiple threads to do my job serially but each time one can set bitmap to surfaceView. And also have to check that:

No Old byte of Array shouldn't be draw on surfaceView.

I think I have to write that code using a synchronize lock. And check for a boolean variable isWorkingOnFrame is true.

Can someone explain me how to use multiple threads in series but at one time one can do its work.

private android.hardware.Camera.PreviewCallback previewCallback = new android.hardware.Camera.PreviewCallback()
    {
        public void onPreviewFrame(byte abyte0[] , Camera camera)
        {   
            try
            {
               Thread.sleep(1L);
            }
            catch (InterruptedException interruptedexception)
            {
                return;
            }

            int[] rgbData =  YuvUtils.myDecodeGreyscale(abyte0, widthPreview, heightPreview, imageBrightness, nonGreencolorOffset, greenColorOffset);  ///it is working...

            editedBitmap.setPixels(rgbData, 0, widthPreview, 0, 0, widthPreview, heightPreview);

            if(CameraStatik.cameraId==CameraInfo.CAMERA_FACING_FRONT)
            {   
                matrix.setRotate(270F);
            }

            finalBitmap = Bitmap.createBitmap(editedBitmap, 0, 0, widthPreview, heightPreview, matrix, true);

            if(saveCurrentFrame)
            {
                saveCurrentFrame =false;

                new BitmapSaver(ctx, finalBitmap).start();
            }

            drawView.setBitmapToDraw(finalBitmap);
        }
    };

I simply want to make this code work efficiently.


回答1:


Solve it in the java way! Use the Executor interface along with Runnable.

First, get a ExecutorService (which implements the Executor interface) with Executors.newSingleThreadExecutor(), and then, put your Threads to work.

Example:

public YourClass extends Activity {
    // Other methods like onCreate() variable declarations and so on.
    // ...

    private void runOnThread() {
        Executor exe = Executors.newSingleThreadExecutor();
        exe.execute(new Runnable() { 
            public void run() { 
                // Do whatever you want to do.
            } 
        });
    }
    // Other methods...
    // ...
}

You can read more about Executor here.

Or like it was said on the comments, you can take a look at ThreadPoolExecutor and on this tutorial.



来源:https://stackoverflow.com/questions/31966790/how-to-make-threads-work-in-series

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!