Anybody can explain how it is going to work and why it works soclass A{ int a; A() { a=20; }}class Myth{public static void main(String S[]){final A ob=new A(); class B extends Thread { B() { start(); } public void run() { for(int i=0;i

Showing Answers 1 - 2 of 2 Answers

op is ValueB:20ValueC:21ValueB:22ValueC:23Both Classes B and C extend thread, So when constructor is called of each class will create a new thread, which you have started by start().So flow of execution can be explainedmain thread is started first, then thread for class B is started when obj of class B is created.it enters a loop in which prints value variable a of Object obas ValueB:20, it then increments variable a of Object ob by 1 i.e a=21 and then thread B sleeps for a 1000ms before next time executing loop,In the meantime the main thread has continued execution to next line i.e created obj of class C which starts a new thread for class C,it enters a loop in which prints value variable a of Object ob as ValueC:21, it then increments variable a of Object ob by 1 i.e a=22and then thread C sleeps for a 1000ms before next time executing loop.Now 1000ms sleep time of Thread B will get over before Thread C as it has slept earlier,after it's sleep time gets over it prints value of a as ValueB:22 and increment a by one i.e a=23 and sleeps again. During this sleep time the first Sleep time of thread C gets over and it prints value of a as Value C:23, then increments a and sleeps again. So on, Rajesh hope u understand. Try incrementing no of times loops e.g 10 are executed and keep sleep time of thread C (e.g 200 ms)less than of Thread B you'll see thread C will get complete its execution before B.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions