如何在线程被中断后确保通过某个地方?

时间:2016-05-12 13:33:20

标签: android multithreading interrupted-exception android-runonuithread

我在ui计划中为动画更改图像创建了一个线程。单击按钮时将中断,并设置固定图像。 但是如果runOnUiThread中的setImage在onClick中的setImage之后意外发生,那么它将是错误的图像。

这段代码中是否有任何方法可以确保在从InterruptedException返回后通过某处。 (我不希望ui线程有任何延迟)

请帮助谢谢!

    thread = new Thread(){
        @Override
        public void run() {
            while(!this.isInterrupted()){
                for(int i=0; i<imageList.size(); i++){
                    if(getActivity()==null) return;
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            ImageViewAnimatedChange(getActivity().getApplication(),
                                        imgFunction, imageList.get(j), 0);
                        }
                    });
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Log.e(TAG, e.toString());
                        return;
                    }
                }
            }
        }
    };

// onClick

                        if(thread!=null) {
                            thread.interrupt(); // catch interruptException
                            thread = null;
                            imgFunction.setImageResource(R.drawable.selector);
                        }

编辑: 我按照建议改写了这部分。

public class asyncTask extends AsyncTask<String, String, String>{
    @Override
    protected String doInBackground(String... params) {
        Log.d(TAG, "doInBackground");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Log.w(TAG, e.toString());
            return null;
        }

        final List<Bitmap> imageList = getImageList();
        if(imageList.isEmpty()) return null;
        Log.d(TAG, "start while ");

        while(!isCancelled()){
            Log.d(TAG, "while:" +Boolean.toString(isCancelled()));

            for(int i=0; i<imageList.size()+1; i++){
                final int j=i;
                Log.d(TAG, "for" + Integer.toString(j));

                if (j == imageList.size())
                    publishProgress(“ok”);
                else
                    publishProgress(Integer.toString(i));

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Log.w(TAG, e.toString());
                    return null;
                }
            }
        }
        Log.d(TAG, "while end");
        return null;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        QUtil.logE(TAG, "onPostExecute");
        imgFunction.setImageResource(R.drawable.selector);
    }

    @Override
    protected void onProgressUpdate(String... value) {
        super.onProgressUpdate(value);
        Log.d(TAG, "onProgressUpdate" + value[0]);
        if(getActivity()==null || isCancelled()) return;
        if(value[0]==“ok”)
            ImageViewAnimatedChange(getActivity().getApplication(),
                    imgFunction, null, R.drawable.selector);
        else
            ImageViewAnimatedChange(getActivity().getApplication(),
                    imgFunction, getImageList().get(Integer.parseInt(value[0])), 0);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        Log.e(TAG, "onCancelled");
        try {
            Thread.sleep(60);
        } catch (InterruptedException e) {
            Log.w(TAG, e.toString());
        }
        imgFunction.setImageResource(R.drawable.selector);
    }
}

//启动

iftttAsyncTask = new IftttAsyncTask().execute("");

//结束onClick

if(asyncTask!=null) {
                            asyncTask.cancel(true); // catch interruptException
                            threadIfttt = null;
                        }

然后有时工作有时不起作用, “doInBackground”没有睡觉时不能正常工作!它确实进入onCancel但没有真正取消,我用isCanceled()得到了错误 记录照片如下 enter image description here

1 个答案:

答案 0 :(得分:0)

使用AsyncTask进行此类后台工作可能会更好,因为它允许您根据任务是否继续执行单独的UI操作。

例如,在下面的示例AsyncTask中:

public class TestTask extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... args) {

        String input = args[0];
        String output = "simulated return value";

        return output;
    }

    protected void onPostExecute(String result) {
        //if your background operation succeeds, you 
        //would update your image here
    }

    protected void onCancelled() {
       //if your task is cancelled, update your UI with the
       //default image here
    }
}

如果后台操作成功,您将使用在{0}中运行在UI线程上的新图像更新UI。如果中断线程,例如单击按钮,则会取消该任务,而不是onPostExecute(),而是调用onPostExecute()方法。此方法也可以在UI线程上运行,您只需使用默认图像更新UI。