public class Test {
private static void funct(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);
funct (2);
System.out.println(3);
funct (4);
System.out.println(5);
}
}
Every time I run it, I am getting one of the below solutions. Why so?
1
3
5
4
2
1
3
5
2
4
1
3
2
5
4
The order at which the numbers will be printed out is indeterminate in this example. The only thing you know for sure is that 1, 3, and 5 will appear in that order. But where in this arrangement 2 and 4 will come is unknown. The reason for this is you have 3 threads printing out the following number series: (1, 3, 5); (2), and (4). The three threads will be scheduled by the JVM however it determines would be best.
Multithreaded programming is a complex topic, and since it looks like you are just starting to dive into it I would recommend the Concurrency portion of Oracle’s Java tutorial: http://download.oracle.com/javase/tutorial/essential/concurrency/index.html