Creating and Synchronizing in Kotlin

Report a typo

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:

  1. Import: import kotlin.concurrent.thread

    • You use this to import the thread function, enabling the creation of new threads of execution.

  2. Main Function: fun main() { ... }

    • This serves as the main entry point of the program.

  3. 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 thread1 and thread2. The start = true parameter means that the threads should start immediately after creation. The name parameter assigns a name to each thread.

  4. Body of Each Thread:

    • Each thread prints a message to the console: println("${Thread.currentThread().name} is running"). You use Thread.currentThread().name to get the name of the current thread.

  5. Waiting for Threads to Complete:

    • thread1.join()

    • thread2.join()

    • These commands cause the main thread where main runs to wait for the completion of thread1 and thread2. This ensures the program does not end before both threads finish running.

Finally, arrange the lines of code to make the program work correctly.

Reorder lines using drag or arrows. Adjust indentation with left buttons
                }
              
                thread2.join()
              
                thread1.join()
              
                val thread1 = thread(start = true, name = "Thread-1") {
              
                import kotlin.concurrent.thread
              
                println("${Thread.currentThread().name} is running")
              
                println("${Thread.currentThread().name} is running")
              
                val thread2 = thread(start = true, name = "Thread-2") {
              
                // Debugging code or breakpoint here
              
                }
              
                // Debugging code or breakpoint here
              
                }
              
                fun main() {
              

Create a free account to access the full topic