Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import kotlinx.coroutines.*
- import kotlinx.coroutines.sync.Mutex
- import kotlinx.coroutines.sync.withLock
- val threadLocal = ThreadLocal<Int?>()
- //fun main() {
- // val t = TestClass()
- //
- //
- // suspend fun tr() {
- // try {
- // t.m2()
- // } catch (e: Exception) {
- // println("Exception $e")
- // }
- // }
- //
- // val j1 = GlobalScope.launch(threadLocal.asContextElement(value = 1)) {
- // tr()
- // }
- // val j2 = GlobalScope.launch(threadLocal.asContextElement(value = 2)) {
- // tr()
- // }
- //
- // runBlocking { j1.join() }
- // runBlocking { j2.join() }
- // println("end")
- //}
- fun main() {
- val t = TestClass()
- suspend fun tr() {
- try {
- t.m1()
- } catch (e: Exception) {
- println("Exception $e")
- }
- }
- val j1 = GlobalScope.launch(threadLocal.asContextElement(value = 1)) {
- tr()
- }
- runBlocking { j1.join() }
- println("end")
- }
- class TestClass {
- private val mutex = Mutex()
- suspend fun m1() = mutex.withLock(threadLocal.get()) {
- m2()
- println("m1")
- }
- suspend fun m2() = mutex.withLock(threadLocal.get()) {
- delay(3_000L)
- println("m2")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement