Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

doubt on a thread program  RSS feed

 
vishnu bola
Ranch Hand
Posts: 41
1
  • Mark post as helpful
  • send pies
  • 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
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks chris. your explanation really helped.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!