AndroidBites: #2 Threads: Create, Start, Schedule, Prioritize

Threads

Subclassing Thread

class SimpleThread : Thread() {    init {
try {
this.start()
} catch (e: InterruptedException) {
println(e.localizedMessage)
}
}
//there are no checked exceptions in Kotlin
@Throws(InterruptedException::class)
override fun run() {
super.run()
for (i in 1..10) {
println("Hello: $i from ${Thread.currentThread().name}")
sleep(1000) //in MilliSeconds
}
}
}
fun main(args: Array<String>) {
SimpleThread() // thread obj creation + call
}
//===== OR ==================================================fun main(args: Array<String>) {// abstracting everthing away in lambda
val thread = Thread {
for (i in 1..10) {
println("Hello: $i from ${Thread.currentThread().name}")
Thread.sleep(1000) //in MilliSeconds
}
}
thread.start()
}

Implements the Runnable interface

fun main(args: Array<String>) {
Thread(WithRunnable()).start()
}
class WithRunnable : Runnable {
@Throws(InterruptedException::class)
override fun run() {
for (i in 1..10) {
println("Hello: $i from ${Thread.currentThread().name}")
Thread.sleep(1000) //in MilliSeconds
}
}
}
//===== OR ==================================================fun main(args: Array<String>) {
ThreadWithRunnable(Runnable {
for (i in 1..10) {
println("Hello: $i from ${Thread.currentThread().name}")
Thread.sleep(1000) //in MilliSeconds
}
})
}
class ThreadWithRunnable(runnable: Runnable) : Thread(runnable) {
init {
try {
this.start()
} catch (e: InterruptedException) {
println(e.localizedMessage)
}
}
}

Thread Class vs Runnable Interface

fun main(args: Array<String>) {
SimpleThread() // Thread.currentThread().name = "SimpleThreading"
ThreadWithRunnable(Runnable {
for (i in 1..10) {
Thread.currentThread().name = "ThreadWithRunnable"
println("Hello: $i from ${Thread.currentThread().name}")
Thread.sleep(1000) //in MilliSeconds
}
})
Thread {
for (i in 1..10) {
Thread.currentThread().name = "LambdaThreading"
println("Hello: $i from ${Thread.currentThread().name}")
Thread.sleep(1000) //in MilliSeconds
}
}.start()
}

Answer :

Thread Scheduler

Thread Priority

Thread Scheduler in Android

Nice values

Cgroups

Thread Priority in Android

END

Coding enthusiast! love Android #kotlinAlltheWay, want to explore all opportunity around it! CodingMantra: #cleanCoder #TDD #SOLID #designpatterns

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store