Advertisement
Al3XXX

Untitled

Apr 14th, 2023
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.82 KB | None | 0 0
  1. import Api
  2. import kotlinx.coroutines.*
  3. import kotlinx.coroutines.channels.Channel
  4. import okhttp3.OkHttpClient
  5. import retrofit2.Retrofit
  6. import retrofit2.converter.simplexml.SimpleXmlConverterFactory
  7. import retrofit2.create
  8.  
  9. fun main(args: Array<String>): Unit = runBlocking{
  10. //    val channel = Channel<Int>()
  11.     val threads = mutableListOf<Thread>()
  12.  
  13.     val service = Retrofit.Builder()
  14.         .baseUrl("https://google.com/")
  15.         .addConverterFactory(SimpleXmlConverterFactory.create())
  16.         .client(OkHttpClient.Builder().build())
  17.         .build()
  18.         .create<Api>()
  19.  
  20.     coroutineScope {
  21.         launch(Dispatchers.Default) {
  22.             val thread = Thread.currentThread()
  23.             thread.name = "${thread.name} <- THREAD 1"
  24.             threads.add(thread)
  25.             delay(1000)
  26.         }
  27.  
  28.         launch(Dispatchers.Default) {
  29.             val duration = System.currentTimeMillis() + 2000
  30.             val thread = Thread.currentThread()
  31.             thread.name = "${thread.name} <- THREAD 2"
  32.             threads.add(thread)
  33.  
  34.             while (duration > System.currentTimeMillis()) { }
  35.         }
  36.  
  37.         launch(Dispatchers.IO) {
  38.             val thread = Thread.currentThread()
  39.             thread.name = "${thread.name} <- RETROFIT"
  40.             threads.add(thread)
  41.             try {
  42.                 service.longResponse().execute() // ะฑะตะท suspend
  43.             } catch (e: Exception) {
  44.                 println(e.message)
  45.             }
  46.         }
  47.  
  48.         launch {
  49.             val duration = System.currentTimeMillis() + 2000
  50.             while (duration > System.currentTimeMillis()) {
  51.                 println()
  52.                 threads.forEach {
  53.                     println("${it.name}, state=${it.state}")
  54.                 }
  55.                 delay(100)
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement