简体   繁体   中英

Interrupting active Thread Android

I'm trying to make 2 Threads .

Each Thread can interrupt the other one, the two can't be running at the same time .

I've tried to use the function Thread.interrupt(), but this not trigger an exception inside the Thread.

how can I stop a running Thread at any moment? I only found solutions that involve sleeping threads or myths that Thread.Interrupt() trigger an exception, not only a flag.

val toTransparent: Thread = (object : java.lang.Thread() {
    override fun run() {
        try {
            if (toOpaque.isAlive)
                toOpaque.interrupt()
            while (opacity > 0) {
                sleep(1)
                activityForUI.runOnUiThread() {
                    searchBarEmpresa_linearLayout.background.alpha = opacity
                }
                opacity--
            }
        } catch (e: InterruptedException) {
            Thread.currentThread().interrupt()
            return
        }
    }
})

val toOpaque: Thread = (object : Thread() {
    override fun run() {
        try {
            if (toTransparent.isAlive)
                toTransparent.interrupt()
            while (opacity < 255) {
                sleep(1)
                activityForUI.runOnUiThread() {
                    searchBarEmpresa_linearLayout.background.alpha = opacity
                }
                opacity++
            }
        } catch (e: InterruptedException) {
            Thread.currentThread().interrupt()
            return
        }
    }
})

Calling Thread.Interrupt() from outside the thread being stopped it's generally not a good approach to deal with threads, because it can possibly catch the Thread in some intermediate state, dealing with system resources.

Better create some variables like isThread1AllowedToRun and check for its value:

while (isThread1AllowedToRun) {
    ...
    Thread.sleep(20, 0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM