Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Thread in Kotlin

First of all, I'm new in Kotlin, so please be nice :). It's also my first time posting on StackOverflow

I want to literally STOP the current thread that I created but nothing works.

I tried quit(), quitSafely(), interrupt() but nothing works.

I created a class (Data.kt), in which I create and initialize a Handler and HandlerThread as follows :

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
    }
}

And now, in my DataManager, I use these to do asynchronous things :

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(.........)
        }
    }
}

Now, in my MainActivity, I made 2 buttons :

  1. One for running the function getSomething()
  2. The other one is used for switching to another 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()
}

Is there a way to stop the thread, because when I switch to my second View, print("Hello World") is still triggered, unfortunately.

Thanks for helping me guys I hope that you understand !

like image 518
Manu13k Avatar asked Nov 20 '25 03:11

Manu13k


1 Answers

A thread needs to periodically check a (global) flag and when it becomes true then the thread will break out from the loop. Java threads cannot be safely stopped without its consent.

Refer to page 252 here http://www.rjspm.com/PDF/JavaTheCompleteReference.pdf that describes the true story behind the legend.

I think that a truly interruptible thread is only possible through the support of the operating system kernel. The actual true lock is held deep down by the CPU hardware microprocessor.

like image 100
eigenfield Avatar answered Nov 25 '25 00:11

eigenfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!