Creating and Managing Threads in Kotlin to Control Execution Order

Report a typo

Now, let's inspect the sequential flow of the code:

  1. Importing the Mandatory Class: Initially, you import the kotlin.concurrent.thread class; it supplies helpful functions for interacting with threads in Kotlin.

  2. Defining the main Function: Next, you define the main function; it serves as the application's starting point.

  3. Creating Threads:

    • thread1: You create the first thread, but it does not start executing its tasks right away (start = false). This thread prints out a message consisting of its name.

    • thread2: In a similar fashion, the second thread gets created but doesn't initiate at once; it prints a message with its name.

  4. Executing the Threads:

    • When you call thread1.start(), the first thread begins.

    • Similarly, thread2.start() triggers the second thread.

  5. Waiting for Thread Completion:

    • Upon calling thread1.join(), the main thread (which runs the main function) halts until thread1 ends.

    • Calling thread2.join() operates similarly; the main thread stops until thread2 is complete.

Following this code execution, both threads (thread1 and thread2) operate concurrently. Each one prints its message on the console; the main thread then waits for the other two threads to finish before ending the program's execution.
Now, you need to organize the lines of code correctly to achieve the successful execution of the program.

Reorder lines using drag or arrows. Adjust indentation with left buttons
                }
              
                println("Thread 2 is running on ${Thread.currentThread().name}")
              
                }
              
                fun main() {
              
                thread1.start()
              
                thread1.join()
              
                import kotlin.concurrent.thread
              
                }
              
                thread2.start()
              
                val thread2 = thread(start = false) {
              
                val thread1 = thread(start = false) {
              
                println("Thread 1 is running on ${Thread.currentThread().name}")
              
                thread2.join()
              

Create a free account to access the full topic