• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread Doubt

 
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Why the output is
i = 0, i * i = 0
i = 1, i * i = 1
i = 2, i * i = 4
*
**
***
****
and so on. After control coming to line1 how the control flows? Why is it not completing loop1 first? doing simultaneously both?. This is becuase of Threads I know but someone explain me pl.
Thanks.
 
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At line1 control splits in two threads each executing a loop. If you reduce the no. of iteration in each loop to (say) 5 and run this programs quite a few time, you will see that output is unpredictable because both loops are executing at the same time....
[ September 26, 2002: Message edited by: Barkat Mardhani ]
[ September 26, 2002: Message edited by: Barkat Mardhani ]
 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Every process in java is executed in a thread. So when you type "java ThreadDemo" a thread is atrted which executes the code inside main. Lets call this T1.
Now when you say "mt.start()" the thread no.2 (T2) starts up parallely. After this there is no certainity to the execution life time of the two threads. They don't share any variable and hence there is no scope of waiting. And it is not certain that the output will be same always. Infact i executed the same program thrice and got totally different result the third time.
The cpu is shared by the two threads according to Java scheduling system which is based on priority.
 
The overall mission is to change the world. When you've done that, then you can read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic