6 minutes read

We've already learned how to start a new thread by simply invoking the start method on a corresponding object. However, sometimes it is necessary to manage the lifecycle of a thread while it's working rather than just start it and leave it be.

In this topic, we will consider two commonly used methods in multithreading programming: sleep() and join(). Both methods may throw an InterruptedException, which is omitted here for brevity.

Sleeping

The method Thread.sleep() causes the currently executing thread to suspend execution for the specified number of milliseconds. This is an efficient means of making processor time available for the other threads of an application or other applications that might be running on a computer.

We will often use this method throughout our educational platform to simulate expensive calls and difficult tasks.

println("Started")

Thread.sleep(2000) // suspend current thread for 2000 milliseconds
         
println("Finished")

Let's see what this code does. At first, it prints "Started". Then, the current thread is suspended for 2000 milliseconds (it may be longer, but not less than indicated). Eventually, the thread wakes up and prints "Finished".

Another way to make the current thread sleep is to use the special class TimeUnit from the package java.util.concurrent:

  • TimeUnit.MILLISECONDS.sleep(2000) performs Thread.sleep for 2000 milliseconds;

  • TimeUnit.SECONDS.sleep(2) performs Thread.sleep for 2 seconds;

There are more existing periods: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, and DAYS. For example:

import java.util.concurrent.TimeUnit

println("Started")
TimeUnit.SECONDS.sleep(2) // suspend current thread for 2 second
println("Finished")

Joining

The join method forces the current thread to wait for the completion of another thread on which the method was called. In the following example, the string "The end" will not be printed until the thread terminates.

fun main() {
    val thread: Thread = thread(...)
    println("The start")

    thread.start() // start thread

    println("Do something useful")

    thread.join()  // waiting for thread to die

    println("The end")
}

The overloaded version of the join method takes the waiting time in milliseconds:

thread.join(2000)

This is used to avoid waiting for too long or even infinitely in case the thread is hung.

Let's consider another example. The Worker class is developed to solve "a difficult task" simulated by the sleep:

class Worker : Thread() {
    override fun run() {
        println("Starting a task")
        sleep(2000) // it solves a difficult task
        println("The task is finished")
    }
}

Here is the main function where the main thread waits for the completion of worker.

fun main() {
    val worker = Worker()
    worker.start() // start the worker
    Thread.sleep(100)
    println("Do something useful")

    worker.join(3000)  // waiting for the worker
    println("The program stopped")
}

The main thread waits for worker and cannot print the message The program stopped until worker terminates or the timeout is exceeded. We know exactly only that Starting a task precedes The task is finished and Do something useful precedes The program stopped. There are several possible outputs.

The first possible output (the task is completed before the timeout is exceeded):

Starting a task
Do something useful
The task is finished
The program stopped

The second possible output (the task is completed before the timeout is exceeded):

Do something useful
Starting a task
The task is finished
The program stopped

The third possible output:

Do something useful
Starting a task
The program stopped
The task is finished

The fourth possible output:

Starting a task
Do something useful
The program stopped
The task is finished

Conclusion

In this topic, we've learned two useful methods join and sleep, which allow us to manage the lifecycle of a thread. Both methods may throw an InterruptedException, so be careful when using them. Let's practice our knowledge now!

62 learners liked this piece of theory. 3 didn't like it. What about you?
Report a typo