首先,我是 Kotlin 的新手,所以请多关照 :)。 这也是我第一次在 StackOverflow 上发帖
我想从字面上停止我创建的当前线程,但没有任何效果。
我尝试了 quit()
、quitSafely()
、interrupt()
但没有任何效果。
我创建了一个类 (Data.kt
),我在其中创建并初始化了一个 Handler
和 HandlerThread
,如下所示:
class Dispatch(private val label: String = "main") {
var handler: Handler? = null
var handlerThread: HandlerThread? = null
init {
if (label == "main") {
handlerThread = null
handler = Handler(Looper.getMainLooper())
} else {
handlerThread = HandlerThread(label)
handlerThread!!.start()
handler = Handler(handlerThread!!.looper)
}
}
fun async(runnable: Runnable) = handler!!.post(runnable)
fun async(block: () -> (Unit)) = handler!!.post(block)
fun asyncAfter(milliseconds: Long, function: () -> (Unit)) {
handler!!.postDelayed(function, milliseconds)
}
fun asyncAfter(milliseconds: Long, runnable: Runnable) {
handler!!.postDelayed(runnable, milliseconds)
}
companion object {
val main = Dispatch()
private val global = Dispatch("global")
//fun global() = global
}
}
现在,在我的 DataManager
中,我使用它们来执行异步操作:
fun getSomething(forceNetwork: Boolean ) {
val queue1 = Dispatch("thread1") // Create a thread called "thread1"
queue1.async {
for (i in 0..2_000_000) {
print("Hello World")
// Do everything i want in the current thread
}
// And on the main thread I call my callback
Dispatch.main.async {
//callback?.invoke(.........)
}
}
}
现在,在我的 MainActivity
中,我制作了 2 个按钮:
- 一个用于运行函数
getSomething()
- 另一个用于切换到另一个 Controller View :
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
DataManager.getSomething(true)
}
val button2 = findViewById<Button>(R.id.button2)
button2.setOnClickListener {
val intent = Intent(this, Test::class.java) // Switch to my Test Controller
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(intent)
finish()
}
有没有办法停止线程,因为不幸的是,当我切换到第二个 View 时,print("Hello World")
仍然被触发。
谢谢你们帮助我,希望你们能理解!
最佳答案
线程需要定期检查(全局)标志,当它变为真时,线程将从循环中跳出。未经其同意,Java 线程无法安全停止。
请参阅此处的第 252 页 http://www.rjspm.com/PDF/JavaTheCompleteReference.pdf描述了传说背后的真实故事。
我认为只有操作系统内核的支持才能实现真正的可中断线程。实际真正的锁定由 CPU 硬件微处理器深深地控制着。
关于multithreading - 在 Kotlin 中停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49988340/