Davide Cerbo

Dec 16, 2019

4 min read

Playing with Structured concurrency in Kotlin

Photo by Jeff Prieb from FreeImages
10 i = 0
20 i = i + 10
30 PRINT "i: " + i
40 IF (i < 100) GOTO 20
int i = 0;
while(i < 100){
i = i + 10;
print("i: " + i);
}
fun main()  {
var playerOne = AtomicInteger();
var playerTwo = AtomicInteger();
thread {
println("Start match - ${Thread.currentThread().name}")
thread {
(1..10).forEach {
Thread.sleep(Random.nextLong(10, 200))
println("P1 $it - ${Thread.currentThread().name}")
playerOne.incrementAndGet()
}
}
thread {
(1..10).forEach {
Thread.sleep(Random.nextLong(10, 200))
println("P2 $it - ${Thread.currentThread().name}")
playerTwo.incrementAndGet()
}
}
Thread.sleep(500)
Thread.currentThread().interrupt();
println("End match! - ${Thread.currentThread().name}")
when {
playerOne.get() > playerTwo.get() -> println("P1 wins")
playerOne.get() < playerTwo.get() -> println("P2 wins")
playerOne.get() == playerTwo.get() -> println("Draw!")
}
}
println("end - ${Thread.currentThread().name}")
}
fun main() = runBlocking {
var playerOne = AtomicInteger();
var playerTwo = AtomicInteger();
launch {
println("Start match - ${Thread.currentThread().name}")
launch {
(1..10).forEach {
delay(Random.nextLong(10, 200))
println("P1 $it - ${Thread.currentThread().name}")
playerOne.incrementAndGet()
}
}
launch {
(1..10).forEach {
delay(Random.nextLong(10, 200))
println("P2 $it - ${Thread.currentThread().name}")
playerTwo.incrementAndGet()
}
}
delay(500)
cancel()
println("End match! - ${Thread.currentThread().name}")
when {
playerOne.get() > playerTwo.get() -> println("P1 wins")
playerOne.get() < playerTwo.get() -> println("P2 wins")
playerOne.get() == playerTwo.get() -> println("Draw!")
}
}
println("end - ${Thread.currentThread().name}")
}
fun main() = runBlocking {
launch {
println("Start - ${Thread.currentThread().name}")
launch {
(1..5).forEach {
delay(100)
println("A $it - ${Thread.currentThread().name} ")
}
}
launch {
(1..5).forEach {
delay(200)
println("B $it - ${Thread.currentThread().name} ")
}
}
}.invokeOnCompletion {
println("Complete! - ${Thread.currentThread().name}")
}
println("End main method - ${Thread.currentThread().name}")
}

More on Kotlin Coroutine

Further reading