Created
April 4, 2020 19:01
-
-
Save magdamiu/3b06291cb681745455e9464eef788141 to your computer and use it in GitHub Desktop.
Setting a custom pool of threads by using the asCoroutineDispatcher function on Java’s ExecutorService.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import java.util.concurrent.Executors | |
suspend fun suspendTask1() { | |
println("Start task1 | Thread ${Thread.currentThread()}") | |
yield() | |
println("End task1 | Thread ${Thread.currentThread()}") | |
} | |
suspend fun suspendTask2() { | |
println("Start task2 | Thread ${Thread.currentThread()}") | |
yield() | |
println("End task2 | Thread ${Thread.currentThread()}") | |
} | |
fun main() { | |
Executors.newSingleThreadExecutor().asCoroutineDispatcher().use { context -> | |
println("Start main") | |
runBlocking { | |
launch(context) { suspendTask1() } | |
launch { suspendTask2() } | |
println("Called task1 and task2 from ${Thread.currentThread()}") | |
} | |
println("End main") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment