没有将对象添加到Application类的线程内的ArrayList中

时间:2018-07-01 07:37:13

标签: android kotlin android-application-class

我正在与Kotlin一起开发Android应用程序。

这是我在实例化应用程序时试图运行的代码

class SpeechApp: Application() {
    var isDictionaryRead = false
    lateinit var wordslist : ArrayList<String>

    override fun onCreate() {
        super.onCreate()
        wordslist = ArrayList()

        Thread {
            Runnable {
                execute()
            }
        }.start()
    }

    fun execute() {
        val inputStream = assets.open("words.txt")
        val reader = BufferedReader(InputStreamReader(inputStream))

        var line = reader.readLine()
        while (line != null) {
            Log.i("Read" , line)
            wordslist.add(line)
            line = reader.readLine()
        }
        isDictionaryRead = true
    }
}

我希望此代码能正常工作,但是在我的日志中,我看不到任何添加了标签Read的行。但是,如果我像这样在线程外调用execute():

class SpeechApp: Application() {
    var isDictionaryRead = false
    lateinit var wordslist : ArrayList<String>

    override fun onCreate() {
        super.onCreate()
        wordslist = ArrayList()

        execute()
    }

    fun execute() {
        val inputStream = assets.open("words.txt")
        val reader = BufferedReader(InputStreamReader(inputStream))

        var line = reader.readLine()
        while (line != null) {
            Log.i("Read" , line)
            wordslist.add(line)
            line = reader.readLine()
        }
        isDictionaryRead = true
    }
}

我在logcat中可以看到很多带有“ Read”标签的行。我不希望它以这种方式工作,因为在我看到MainActivity之前有大约5s的可见滞后,因为系统正忙于处理words.txt中的479k单词。

如何使execute()在线程内工作?

1 个答案:

答案 0 :(得分:1)

Runnable实际上永远不会运行。而是手动运行它或使用适当的构造函数:

Thread { execute() }.start()

Thread(::execute).start()

Thread(Runnable {
    execute()
}).start()

Thread {
    Runnable {
        execute()
    }.run()
}.start()

当不为构造函数使用SAM转换时,更容易看到问题的原因:

Thread(object : Runnable {
    override fun run() {
        Runnable {
            execute()
        }
    }
}).start()