How to make threads work in Series

276 Views Asked by At

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

There are 1 best solutions below

7
On

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.