1.1.50.30. fejezet, Szálkezelés és Coroutine

Szálak

package hu.infokristaly
 
import kotlin.concurrent.thread
 
class MyThread : Runnable {
    override fun run() {
        var times : Int = 0
        while (true) {
            println("Thread : ${Thread.currentThread().name} : $times")
            Thread.sleep(1000)
            times++
        }
    }
}
 
fun main() {
    println("Starter thread name: ${Thread.currentThread().name}")
 
    val myThread : MyThread = MyThread()
    Thread(myThread).start()
 
    thread() {
        var times : Int = 0
        while (true) {
            println("Thread : ${Thread.currentThread().name} : $times")
            Thread.sleep(500)
            times++
        }
    }
}

CoRoutine-ok

(github)

Függőségek közé fel kell venni:

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0")
fun main() {
    runBlocking {
        var result1: Deferred<List<String>> = async() {
            println("Request started from thread (${Thread.currentThread().name})")
            withContext(Dispatchers.IO) {
                val result = getDataFromServer("https://integrity.hu", 1,5)
                return@withContext result
            }
        }
 
        var result2: Deferred<List<String>> = async() {
            println("Request started from thread (${Thread.currentThread().name})")
            withContext(Dispatchers.IO) {
                val result = getDataFromServer("https://infokristaly.hu",6,10)
                return@withContext result
            }
        }
 
        println(result1.await().union(result2.await()).toList().toString())
    }
}
 
suspend fun getDataFromServer(url:String, from:Int, to: Int): List<String> {
    println("Data request from server $url started(${Thread.currentThread().name})")
    delay(2000)
    val result = mutableListOf<String>()
    for(i in from..to) {
        result.add("String$i")
    }
    return result
}

Dispatcher különböző feladatokra

  • Dispatchers.IO: fájl műveletekre, hálózati lekérdezésekre
  • Dispatchers.Default: CPU igényes feladatokra

Egyszerűbben

suspend fun funA(a: Int): Int {
    println("Thread a: ${Thread.currentThread().name}")
    delay(1000)
    return a
}
 
suspend fun funB(b: Int): Int {
    println("Thread b: ${Thread.currentThread().name}")
    delay(1000)
    return b
}
 
fun sum(a: Int,b: Int): Int {
    var sum = 0
    runBlocking {
        val jobA = async { withContext(Dispatchers.IO){ funA(a) } }
        val jobB = async { withContext(Dispatchers.IO){ funB(b) } }
        runBlocking{
            sum = jobA.await() + jobB.await()
        }
    }
    return sum
}

sum(1,2) // 3

Kapcsolódó hivatkozások