java - Android AsyncTask异常和onPostExecute

标签 java android multithreading asynchronous android-asynctask

我有两个 AsyncTask 类。 第一:

private class NotationChanger extends AsyncTask <Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        synchronized(mutex) {
            try {
                this.infixToPostNotation();
            } catch(ParseErrorException e) {
                Log.i("Parse Error Exception", e.getMessage());
                changedNotationError = true;
            }
            finally {
                mutex.notify();                         //Calculator waits while notation is being changed
            }                                           //So we should wake it                      
        }
        return null;
    }


    @Override 
    protected void onPreExecute() {
        super.onPreExecute();
        changedNotation = false;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        changedNotation = true;
    } 

    ...
}

第二:

private class Calculator extends AsyncTask <Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {
        synchronized(mutex) {
            while(!changedNotation) {
                try {
                    mutex.wait();
                }   catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        Log.i("Calculation", "waked");

        if(!changedNotationError) {
            try {
                this.calculatePoints();
            } catch (CalculateException e) {
                Log.i("Calculate exception", e.getMessage());
            }
        }
        else {
            changedNotationError = false;
        }

        return null;
    }

    ...
}

正如您所看到的,当 NotationChanger 完成其工作时,它会唤醒 Calculator 类。它工作正常,没有异常(exception)。当我在 NotationChanger 类中收到 ParseErrorException 时,不会调用 onPostExecute 方法。

如果我搬家

changedNotation = true; 

从onPostExecute函数到finally block 每次都运行良好。这是否意味着 doInBackground 中的异常中断了 onPostExecute 方法的调用,或者我什么都不明白?

最佳答案

如果计算器先运行,并在 doInBackground() 中等待。 我认为你的NotationChanger无法进入doInBackground()。 根据我的经验,所有 AsyncTask 都只使用一个线程来工作。

关于java - Android AsyncTask异常和onPostExecute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431743/

相关文章:

java - Spring race conditions 单例服务有状态还是无状态

java - 垃圾邮件保护 onclick()

java - XPath 歧义

java - 无法在 Android 中写入文件,只读文件系统

WPF System.InvalidOperationException : The calling thread cannot access this object because a different thread owns it

java - 在哪里关闭多线程的连接/文件/日志?

java - Java 中可序列化类的不可序列化异常

java - 导出 Swing 应用程序后没有图标

Android为AppWidget设置不同的布局

java - 解析数据时出错[java.lang.String类型的值p无法转换为JSONObject