Sobes.tech
Middle

How to implement multithreading in Kotlin?

sobes.tech AI

Answer from AI

Multithreading in Kotlin can be implemented in several ways:

  1. Standard Java Threads:

    // Implementing the Runnable interface
    class MyRunnable : Runnable {
        override fun run() {
            // Code to be executed in a separate thread
            println("Hello from thread: ${Thread.currentThread().name}")
        }
    }
    
    fun main() {
        // Create an instance of Runnable
        val runnable = MyRunnable()
        // Create a Thread object with Runnable
        val thread = Thread(runnable)
        // Start the thread
        thread.start()
    }
    

    Or using a lambda expression:

    fun main() {
        val thread = Thread {
            // Code to be executed in a separate thread
            println("Hello from thread: ${Thread.currentThread().name}")
        }
        thread.start()
    }
    
  2. Kotlin Coroutines: This is the recommended and more modern approach in Kotlin, providing lightweight multithreading.

    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        // Create a new coroutine in the global scope
        launch {
            delay(1000L) // Non-blocking delay for 1 second
            println("Hello from coroutine")
        }
        // Main thread continues to work
        println("Hello from main thread")
        // runBlocking waits for all nested coroutines to complete
    }
    

    Examples of different coroutine builders:

    • launch: Starts a new coroutine without a return value.
    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        launch {
            println("This coroutine just performs an action")
        }
    }
    
    • async: Starts a new coroutine that returns a result via Deferred.
    import kotlinx.coroutines.*
    
    fun main() = runBlocking {
        val deferredResult = async {
            delay(1000L)
            "Result from coroutine"
        }
        val result = deferredResult.await() // Wait for the result
        println(result)
    }
    
  3. RxKotlin/RxJava: Reactive programming also allows working with asynchronous operations and multithreading using schedulers.

    import io.reactivex.rxjava3.core.Observable
    import io.reactivex.rxjava3.schedulers.Schedulers
    
    fun main() {
        Observable.just("Asynchronous element")
            .subscribeOn(Schedulers.io()) // Execute subscription in I/O thread
            .observeOn(Schedulers.computation()) // Observe results in computation thread
            .subscribe { item ->
                println("Received: $item on thread ${Thread.currentThread().name}")
            }
    
        Thread.sleep(2000) // Wait for asynchronous operations to complete
    }
    

The choice of method depends on the specific task. For most modern Kotlin applications, coroutines are preferred due to their lightweight nature, ease of use, and built-in language support. Java threads may be suitable for lower-level control, and reactive libraries for working with data streams.

How to implement multithreading in Kotlin? — Kotlin - sobes.tech