Kotlin stworzył lżejszą alternatywę dla natywnych wątków – coroutines. Jest to w gruncie rzeczy programowa obsługa wątków (zajrzyj tutaj po więcej na ten temat).
Kod oparty o wątki (czysta Java)
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
int taskId = i;
new Thread(() -> {
System.out.println("Starting task " + taskId + " on thread " + Thread.currentThread().getName());
try {
Thread.sleep(500); // Simulate a short delay
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished task " + taskId + " on thread " + Thread.currentThread().getName());
}).start();
}
// Keep the main thread alive to let other threads complete
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Kod oparty o wątki (Kotlin)
import kotlin.concurrent.thread
fun main() {
// Start three tasks concurrently using Threads
for (i in 1..3) {
thread {
println("Starting task $i on thread ${Thread.currentThread().name}")
Thread.sleep(500) // Simulate a short delay
println("Finished task $i on thread ${Thread.currentThread().name}")
}
}
// Keep the main thread alive to let other threads complete
Thread.sleep(1000)
}
Kod oparty o coroutines
import kotlinx.coroutines.*
fun main() = runBlocking {
// Start three tasks concurrently using Coroutines
for (i in 1..3) {
launch {
println("Starting task $i on coroutine ${Thread.currentThread().name}")
delay(500) // Simulate a short delay
println("Finished task $i on coroutine ${Thread.currentThread().name}")
}
}
// No need for additional delay, as `runBlocking` waits for all coroutines to finish
}