Thread and Coroutines in Kotlin
This commit is contained in:
parent
acf37e52ef
commit
2d3accedcc
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.thread
|
||||
|
||||
class SimpleRunnable: Runnable {
|
||||
|
||||
override fun run() {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.thread
|
||||
|
||||
class SimpleThread: Thread() {
|
||||
|
||||
override fun run() {
|
||||
println("${Thread.currentThread()} has run.")
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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.")
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue