Background threads synchronization
In this recipe, we are going to explore how to work effectively with the JVM Thread
class in a clean way using the Kotlin standard library functions dedicated to running threads in a convenient way. We are going to simulate two long-running tasks and execute them in background threads synchronously.
Getting ready
In this recipe, we are going to make use of the following two functions to simulate long-running operations. The `5 sec long task`()
function:
private fun `5 sec long task`() = Thread.sleep(5000)
and the `2 sec long task`()
function:
private fun `2 sec long task`() = Thread.sleep(2000)
They are both just responsible for blocking a current thread for five and two seconds, respectively, in order to simulate long-running tasks. We will also make use of the predefined function returning the current thread name for debugging purposes:
private fun getCurrentThreadName(): String = Thread.currentThread().name
How to do it...
- Let's start by logging the current...