June 2018
Intermediate to advanced
310 pages
6h 32m
English
We've already seen how to start a new thread in Kotlin. Now let's start a new coroutine instead.
We'll create almost the same example we did with threads. Each coroutine will increment some counter, sleep for a while to emulate some kind of IO, and then increment it again:
val latch = CountDownLatch(10_000)val c = AtomicInteger()val start = System.currentTimeMillis()for (i in 1..10_000) { launch(CommonPool) { c.incrementAndGet() delay(100) c.incrementAndGet() latch.countDown() }}latch.await(10, TimeUnit.SECONDS)println("Executed ${c.get() / 2} coroutines in ${System.currentTimeMillis() - start}ms")
The first way of starting a new coroutine is by using the launch() function. Again, note that this is simply another function ...
Read now
Unlock full access