Created
December 11, 2018 15:27
-
-
Save michaelilyin/6ffc190bd8188f56c795fa5846c9bc38 to your computer and use it in GitHub Desktop.
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.delay | |
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.runBlocking | |
import java.util.concurrent.Executors | |
import java.util.concurrent.atomic.AtomicInteger | |
import kotlin.concurrent.thread | |
import kotlin.system.measureTimeMillis | |
val n = 100 | |
val delay = 1000L | |
fun calcPool() { | |
val int = AtomicInteger(0) | |
val executor = Executors.newWorkStealingPool() | |
val jobs = List(n) { | |
executor.submit { | |
Thread.sleep(delay) | |
int.incrementAndGet() | |
} | |
} | |
jobs.forEach { it.get() } | |
println("Pool: ${int.get()}") | |
} | |
fun calcThreads() { | |
val int = AtomicInteger(0) | |
val jobs = List(n) { | |
thread { | |
Thread.sleep(delay) | |
int.incrementAndGet() | |
} | |
} | |
jobs.forEach { it.join() } | |
println("Threads: ${int.get()}") | |
} | |
fun calcCoroutines() = runBlocking { | |
val int = AtomicInteger(0) | |
val jobs = List(n) { | |
launch { | |
delay(delay) | |
int.incrementAndGet() | |
} | |
} | |
jobs.forEach { it.join() } | |
println("Coroutines: ${int.get()}") | |
} | |
fun main(args: Array<String>) { | |
val coroutinesTotal = measureTimeMillis { | |
calcCoroutines() | |
} | |
println("Time: $coroutinesTotal") | |
println() | |
val threadsTotal = measureTimeMillis { | |
calcThreads() | |
} | |
println("Time: $threadsTotal") | |
println() | |
val poolTotal = measureTimeMillis { | |
calcPool() | |
} | |
println("Time: $poolTotal") | |
println() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment