This article describes threading in Kotlin and introduces Kotlin Coroutines.
The aim of multithreading is to concurrently allow execution of two or more parts of the program.
In the single-threaded approach, tasks are processed in a single sequence. This means that a particular task has to wait for its predecessor to be completed before it can be processed. In reality, this actually means that:
In the multi-threaded approach, tasks are processed concurrently. This means that a particular task does not have to wait for its predecessor to be completed before it can be processed. In multithreading, each part of the program is called a thread and each thread has a unique execution path.
All threads in a process share resources (e.g., memory, data, etc.) Because of this, multithreading can be very economical as our threads share resources instead of accessing these resources in sequential order.
However, multithreading is complicated and building safe multithreaded apps can be quite challenging.
The traditional way is to create threads and run some parts of our programs in these threads. There are several ways to do this in Kotlin.
Thread
classclass MyThread: Thread() { public override fun run() { doSomething() } } ... // some more code // executing val myThread = MyThread() myThread.start()
Runnable
interfaceclass MyRunnableClass: Runnable { public override fun run() { doSomething() } } ... // some more code // executing val runnableThread = Thread(MyRunnableClass()) runnableThread.start()
val lambdaThread = Thread{ doSomething() } ... // some more code // executing lambdaThread.start()
However, traditional threads are costly to maintain and, as a result, are not as effective as we would hope or imagine. However, Kotlin has coroutines, which take care of the costs and complications of parallel programming (or concurrency). They are lightweight efficient threads that are really easy to use.
Coroutines now have a stable library, meaning that there won’t be any code breaking changes to their API.
RELATED TAGS
CONTRIBUTOR
View all Courses