Thread.join()没有按预期工作

时间:2015-12-12 20:19:13

标签: android multithreading

好的,我有一个想要访问.jpg文件的线程,该文件在被另一个线程写入内部存储之前:

ImageSaverThread ist = new ImageSaverThread(mPreview.getmCameraInstance());
ist.start();
File file1 = ist.getOutputMediaFile(1);
try {
    ist.join();
    this.sleep(1);  // This is only for debugging!
} catch (InterruptedException e) {
    e.printStackTrace();
    Log.d("IST ERROR", "ImageSaverThread did not finish!");
    return;
}

File mediaStorageDir = new File(String.valueOf(Environment
    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)));
File file = new File(mediaStorageDir.getPath() + File.separator +
    "IMG_" + "TEST" + ".jpg");
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(file));
short[][] image = getByteImage(bitmap);

然而,当我运行我的代码时,我收到一个错误,因为我的位图是一个null对象。要加载的图像显然尚不可用。当我放置Thread.sleep(50)而不是ist.join()时,一切正常,因为我等待50毫秒才能完成ImageSaverThread

这里有任何帮助吗?

修改

这就是ImageSaverThread的作用:

public void run() {
    PictureCallback mPicture = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
            if (pictureFile == null) {
                return;
            }

            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                Log.d("FAIL", "File not found: " + e.getMessage());
            } catch (IOException e) {
                Log.d("FAIL", "Error accessing file: " + e.getMessage());
            }
            camera.stopPreview();
            camera.startPreview();
        }
    };
    mCamera.takePicture(null, null, mPicture);
}

0 个答案:

没有答案