Starting a thread

Doing some work in a different thread can be done in Kotlin the same as in Java, by creating an instance of the Thread class with a Runnable function and then starting it. Kotlin also offers a shortcut function called thread that is a little bit easier to use. It has several default parameters and only needs a lambda that will be executed in the newly created thread:

thread {
//something long running
println("Work done")
}

This is how the thread function is defined in the standard library:

/**
* Creates a thread that runs the specified [block] of code.
*
* @param start if 'true', the thread is immediately started.
* @param isDaemon if 'true', the thread is created as a daemon thread. The Java Virtual Machine exits when
* the only threads running are all daemon threads.
* @param contextClassLoader the class loader to use for loading classes and resources in this thread.
* @param name the name of the thread.
* @param priority the priority of the thread.
*/
public fun thread(
start: Boolean = true,
isDaemon: Boolean = false,
contextClassLoader: ClassLoader? = null,
name: String? = null,
priority: Int = -1,
block: () -> Unit
): Thread

If you are interested in just offloading some work to a background thread, then almost all of these parameters can be left with their default values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.42.116