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.
This is a race condition @Jake. Your
mainis not waiting for the first thread to finish before starting the second. It is starting the first thread which finishes its work beforemaingets 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 yourprintlnstatements which would show it more specifically.FYI: it is recommended to have your classes
implement Runnableas opposed toextends Thread. Then you would do:Also, use of the
ExecutorServicecode is recommended more than using thread directly.