0
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

Ava
  • 5,783
  • 27
  • 58
  • 86

4 Answers4

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

Sean Kleinjung
  • 3,115
  • 2
  • 21
  • 15
1

This is because you have no control over which thread is spawning first. It's decided by the JVM. Only "1,3,5" will be in order since they are executed from main.

This question may be relevant:-

  1. Run java thread at specific times
Community
  • 1
  • 1
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
1

Because your main thread beats the other two threads some of the time. Other times not.

You've got three threads; there's no guarantee which is going to get scheduled to run in any particular order.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
1

Threading and asynchronicity in general are complex topics, but the short of it is that in your case, the threads take a bit to spin up, so they interleave with the other print statements depending on what kind of processor time the JVM (and, in turn, the OS) decides to allocate to those threads.

I highly suggest the book Java Concurrency in Practice, by Brian Goetz and others, if you want to get a really solid handle on what's going on.

trptcolin
  • 2,320
  • 13
  • 16