Prakhar Agrawal Prakhar Agrawal - 13 days ago 13
Java Question

How to run two threads at the same time in java

I am new to java and I am trying to learn about threads.

I am expecting an output of alternate

hello this is thread one
and
hello this is thread two
. but the output I get is as follows:

hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread one
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two
hello this is thread two


Below is my code. Can anyone please help me out to why I am getting this output as opposed to expected. And what is it that I can do to run the two threads in parallel.

public class ThreadDemo {
public static void main(String args[]) {

// This is the first block of code
Thread thread = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread one");
}
}
};

// This is the second block of code
Thread threadTwo = new Thread() {
public void run() {
for (int i = 0; i < 10; i += 2) {
System.out.println("hello this is thread two");
}
}
};

// These two statements are in the main method and begin the two
// threads.
// This is the third block of code
thread.start();

// This is the fourth block of code
threadTwo.start();
}
}

Answer

Depending on the number of CPUs and/or CPU cores, multi-threading may only be simulated by your CPU by giving each thread a certain number of time before another thread is scheduled. See also Wikipedia on "Preemptive Multitasking"

Also, given today's CPUs and many cores and their speed, it may also be that the execution of the first thread already finished before the second one is started.

Also, both threads are battling for the lock in System.out, so they will lock each other out.

Let the threads run for longer times (higher number of iterations), and you will see the interleaving you are expecting.