• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

doubt on a thread program

 
Ranch Hand
Posts: 41
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am new to java and trying to execute the program below
public class BB {

private static void fun(final int i) {
new Thread(new Runnable() {
public void run() {System.out.println(i);}
}).start();
}

public static void main(String[] args) {
System.out.println(1);
fun (2);
System.out.println(3);
fun (4);
System.out.println(5);
}
}
When i run this program output is 1 3 2 5 4 . Can't really understand what's going on with this code? please help
 
Ranch Hand
Posts: 443
3
Eclipse IDE C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
'fun' creates new threads of execution ...
Thread 1 will always in order output 1,3,5. Thread 2 will output 2 sometime after the first thread has output 1 and the third thread will output 4 sometime after the first thread outputs 3.

The answer you get can therefore in fact vary though if you see this depends on your PC.

The more simplistic answer is imagine a person prints 1,3,5 in order but after 1 tells his mate to print 2 anytime he likes and after 3 tells another mate to print 4 any time he likes. Note that if the first mate decides to make a cup of tea first the second mate can get his work done before the second mate (in theory)
 
vishnu bola
Ranch Hand
Posts: 41
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks chris. your explanation really helped.
 
Get off me! Here, read this tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic