You create and launch two parallel threads in our program using the thread function. Each thread, during execution, prints a message indicating it's running. Let's look at the key elements of this code:
Import:
import kotlin.concurrent.threadYou use this to import the
threadfunction, enabling the creation of new threads of execution.
Main Function:
fun main() { ... }This serves as the main entry point of the program.
Creating and Starting Threads:
val thread1 = thread(start = true, name = "Thread-1") { ... }val thread2 = thread(start = true, name = "Thread-2") { ... }Here, you create two threads
thread1andthread2. Thestart = trueparameter means that the threads should start immediately after creation. Thenameparameter assigns a name to each thread.
Body of Each Thread:
Each thread prints a message to the console:
println("${Thread.currentThread().name} is running"). You useThread.currentThread().nameto get the name of the current thread.
Waiting for Threads to Complete:
thread1.join()thread2.join()These commands cause the main thread where
mainruns to wait for the completion ofthread1andthread2. This ensures the program does not end before both threads finish running.
Finally, arrange the lines of code to make the program work correctly.