Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.27 KB | None | 0 0
  1. import kotlinx.coroutines.*
  2. import kotlinx.coroutines.sync.Mutex
  3. import kotlinx.coroutines.sync.withLock
  4.  
  5. val threadLocal = ThreadLocal<Int?>()
  6.  
  7. //fun main() {
  8. //    val t = TestClass()
  9. //
  10. //
  11. //    suspend fun tr() {
  12. //        try {
  13. //            t.m2()
  14. //        } catch (e: Exception) {
  15. //            println("Exception $e")
  16. //        }
  17. //    }
  18. //
  19. //    val j1 = GlobalScope.launch(threadLocal.asContextElement(value = 1)) {
  20. //        tr()
  21. //    }
  22. //    val j2 = GlobalScope.launch(threadLocal.asContextElement(value = 2)) {
  23. //        tr()
  24. //    }
  25. //
  26. //    runBlocking { j1.join() }
  27. //    runBlocking { j2.join() }
  28. //    println("end")
  29. //}
  30.  
  31. fun main() {
  32.     val t = TestClass()
  33.    
  34.     suspend fun tr() {
  35.         try {
  36.             t.m1()
  37.         } catch (e: Exception) {
  38.             println("Exception $e")
  39.         }
  40.     }
  41.  
  42.     val j1 = GlobalScope.launch(threadLocal.asContextElement(value = 1)) {
  43.         tr()
  44.     }
  45.  
  46.     runBlocking { j1.join() }
  47.     println("end")
  48. }
  49.  
  50.  
  51. class TestClass {
  52.     private val mutex = Mutex()
  53.  
  54.     suspend fun m1() = mutex.withLock(threadLocal.get()) {
  55.         m2()
  56.         println("m1")
  57.     }
  58.  
  59.     suspend fun m2() = mutex.withLock(threadLocal.get()) {
  60.         delay(3_000L)
  61.         println("m2")
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement