代码之家  ›  专栏  ›  技术社区  ›  Sparker0i

对象未添加到应用程序类线程内的ArrayList

  •  1
  • Sparker0i  · 技术社区  · 6 年前

    我正在android应用程序开发中与kotlin合作。

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

    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 ,因为系统正忙于处理内部的479k个字 words.txt 是的。

    我该怎么做 execute() 在线里面工作?

    1 回复  |  直到 6 年前
        1
  •  1
  •   tynn    6 年前

    这个 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()