线程需要定期检查(全局)标志,当它变为true时,该线程将退出循环。未经同意,无法安全停止Java线程
首先,我是科特林的新人,所以请保持友好:)这也是我第一次在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”)继续感谢您帮助我,希望您能理解!
首先,我是Kotlin的新手,所以请好心:)这也是我第一次在StackOverflow上发帖,我想立即停止我创建的当前线程,但没有任何效果,我尝试了quit(),...] >
线程需要定期检查(全局)标志,当它变为true时,该线程将退出循环。未经同意,无法安全停止Java线程
线程需要定期检查(全局)标志,当它变为true时,该线程将退出循环。未经同意,无法安全停止Java线程