when we perform an operation on the main thread for more than 5 seconds, it will throw an ANR Error. But here, runblocking and launch are running in the main thread, but it's not throwing ANR Error.

My code snippet:

override fun onCreate(savedInstanceState: Bundle?) { 
super.onCreate(savedInstanceState) 
setContentView(R.layout.activity_coroutine) 
Log.d("test", "Main program started ${Thread.currentThread().name}")                           
runBlocking { Log.d("test", "run blocking ${Thread.currentThread().name}")

     var job =  launch {
            Log.d("test", "launch: ${Thread.currentThread().name}")
          for(i in 1..500){
              println("$i...")
              Thread.sleep(50)
          }
        }

        job.join()
        Log.d("test","Main program ended ${Thread.currentThread().name}")
    }
    Log.d("test","activity oncreate() ended ${Thread.currentThread().name}")
} 
}

I can see the o/p as follows:

Main program started the main

run blocking the main

launch: main 1.. 2.. . . 500

Main program ended

Mainactivity oncreate() ended main

If we perform an operation in Main thread more than 5 seconds, it must throw ANR Error.

0

There are 0 best solutions below