Skip to content

Instantly share code, notes, and snippets.

View MasoudFallahpour's full-sized avatar

Masoud Fallahpour MasoudFallahpour

View GitHub Profile
interface Software {
fun getLicense(): String
}
import kotlinx.coroutines.*
fun main() = runBlocking {
launch(CoroutineName("parent")) {
launch {
println("coroutine1 started")
delay(500)
throw RuntimeException()
}
launch {
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
println("Coroutine started.")
try {
delay(Long.MAX_VALUE)
} catch (ex: CancellationException) {
println("Coroutine cancelled.")
}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch(Dispatchers.Unconfined) {
println("Before delay. Thread name: ${Thread.currentThread().name}")
delay(500)
println("After delay. Thread name: ${Thread.currentThread().name}")
import kotlin.concurrent.thread
fun main() {
repeat(100_000) {
thread {
Thread.sleep(1000L)
println(".")
}
}
}
fun main() = runBlocking {
val job = launch(CoroutineName("parent")) {
println("Launching two coroutines...")
val child1Job = launch {
println("coroutine1: I'm started")
delay(2000)
println("coroutine1: I'm done")
}
launch {
println("coroutine2: I'm started")
fun main() = runBlocking {
val job = launch(CoroutineName("parent")) {
launch {
delay(2000)
println("coroutine1: I'm done")
}
launch {
delay(3000)
println("coroutine2: I'm done")
}
import kotlinx.coroutines.*
fun main() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5 && isActive) { // <-- HERE!
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
import kotlinx.coroutines.*
fun main() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (i < 5) {
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val request = launch(CoroutineName("request")) {
repeat(3) { i ->
launch {
delay((i + 1) * 200L) // variable delay 200ms, 400ms, 600ms