Thread and Coroutines in Kotlin

This commit is contained in:
Alfonso Lentini 2018-10-07 13:08:12 +02:00
parent acf37e52ef
commit 2d3accedcc
4 changed files with 122 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package com.baeldung.thread
class SimpleRunnable: Runnable {
override fun run() {
println("${Thread.currentThread()} has run.")
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.thread
class SimpleThread: Thread() {
override fun run() {
println("${Thread.currentThread()} has run.")
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.thread
import kotlinx.coroutines.experimental.*
import org.junit.jupiter.api.Test
class CoroutineUnitTest {
@Test
fun whenCreateLaunchCoroutineWithoutContext_thenRun() {
val job = launch {
println("${Thread.currentThread()} has run.")
}
runBlocking {
job.join()
}
}
@Test
fun whenCreateLaunchCoroutineWithDefaultContext_thenRun() {
val job = launch(DefaultDispatcher) {
println("${Thread.currentThread()} has run.")
}
runBlocking {
job.join()
}
}
@Test
fun whenCreateLaunchCoroutineWithUnconfinedContext_thenRun() {
val job = launch(Unconfined) {
println("${Thread.currentThread()} has run.")
}
runBlocking {
job.join()
}
}
@Test
fun whenCreateLaunchCoroutineWithDedicatedThread_thenRun() {
val job = launch(newSingleThreadContext("dedicatedThread")) {
println("${Thread.currentThread()} has run.")
}
runBlocking {
job.join()
}
}
@Test
fun whenCreateAsyncCoroutine_thenRun() {
val deferred = async(Unconfined) {
return@async "${Thread.currentThread()} has run."
}
runBlocking {
val result = deferred.await()
println(result)
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.thread
import org.junit.jupiter.api.Test
import kotlin.concurrent.thread
class ThreadUnitTest {
@Test
fun whenCreateThread_thenRun() {
val thread = SimpleThread()
thread.start()
}
@Test
fun whenCreateThreadWithRunnable_thenRun() {
val threadWithRunnable = Thread(SimpleRunnable())
threadWithRunnable.start()
}
@Test
fun whenCreateThreadWithSAMConversions_thenRun() {
val thread = Thread {
println("${Thread.currentThread()} has run.")
}
thread.start()
}
@Test
fun whenCreateThreadWithMethodExtension_thenRun() {
thread(start = true) {
println("${Thread.currentThread()} has run.")
}
}
}