Jake Byman
Jake Byman

Reputation: 563

Compiler logic with Java Multithreading?

So I'm slightly confused as to how multi-threading works. For example, if I create a subclass of Thread called MySub, and this is what it looks like:

public class MySub extends Thread {
   public void run {
      for(int i = 0; i < 5; i++){
         System.out.println(i); 
      }
   }
}

And in the main class I do this:

public static void main(String[] args) {
    Thread m = new MySub();
    Thread m2 = new MySub();
    m.start();
    m2.start();
}

Shouldn't it call the start() method for m, and then go straight to calling the start() method for m2, without waiting for the m thread to finish? Isn't that the point of multithreading?

But in actuality, it prints 0 through 4 from the start() call for m, and then 0 through 4 for the start() call for m2. They didn't go concurrently, they went sequentially, which isn't what I expected. I kind of expected a mess of 0 through 4 numbers.

Upvotes: 1

Views: 107

Answers (1)

Gray
Gray

Reputation: 116918

This is a race condition @Jake. Your main is not waiting for the first thread to finish before starting the second. It is starting the first thread which finishes its work before main gets a chance to start the second thread.

If you tried printing (let's say) 1000 numbers or something that takes more time, you would start to see them interleave. Or you could put a Thread.sleep(10) between your println statements which would show it more specifically.

FYI: it is recommended to have your classes implement Runnable as opposed to extends Thread. Then you would do:

Thread m1 = new Thread(new MySub());
m1.start();

Also, use of the ExecutorService code is recommended more than using thread directly.

Upvotes: 4

Related Questions