我想在方法执行之后再调用它。
现在我有了方法playSimulation(),它做一些计算和输出。在它执行一次之后,我需要无休止地重复它。
这是我的代码片段:
private fun playSimulation() {
// do some calculations
Timer().schedule(3000) {
playSimulation()
}
}这个解决方案不起作用,因为我会遇到并发问题。有时我很幸运,程序没有问题,但在一半的情况下,我得到了一个例外。
Exception in thread "Timer-3" java.lang.ArrayIndexOutOfBoundsException: 9我的问题是如何解决这个问题,最好的架构方法是什么?提前谢谢。
发布于 2022-01-11 18:01:13
尝尝这个
private fun myMethod() {
// do stuff every 1000 milliseconds
Handler(Looper.getMainLooper()).postDelayed({
myMethod()
}, 1000)
}如果需要在某个时候取消它,则需要保留对Runnable和Handler的引用:
private fun myMethod() {
// do stuff every 1000 milliseconds
val handler = Handler(Looper.getMainLooper())
val runnable = { myMethod() }
handler.postDelayed(runnable, 1000)
handler.removeCallbacks(runnable)
}https://stackoverflow.com/questions/70671306
复制相似问题