Kraken
Kraken

Reputation: 24233

Multithreading in Java

Here is my code

public class ThreadLearn{
private static class Check implements Runnable{
    public void run(){

        System.out.printf("\nInCheck %s", Thread.currentThread().getName());
    }
}

public static void main(String[] args){

   Thread t;
   int i=0;
   while(i<2){
      t = new Thread(new GetData());
      t.start();
      System.out.printf("\n%s: ", t.getName());
      i++;
   }

}

}

The output is:

InRun Thread-0
Thread-0:
Thread-1:
InRun Thread-1

I have two questions:

  1. Should not the output be

    InRun Thread-0

    Thread-0:

    InRun Thread-1

    Thread-1:

  2. Once the t.start() is done, will it wait for the run() to be executed and then create the second thread? what if i want to do the following

    while(required)

    new Thread().start();

and in my run method i can have all the stuff that i want the threads to accomplish in parallel so that it doesnt wait for one thread to complete the run method and then create the second thread.

Thanks

Upvotes: 0

Views: 369

Answers (3)

Alex Coleman
Alex Coleman

Reputation: 7326

When the thread is started, it's started. So the two System.out are executed at nearly the exact same time, causing them to sometimes change order

Example:

            ---- thread-0 prints out  
Main thread |--- Prints out ----------- Prints out
                                      |Thread-1 started, prints out

As you can see, the branches will run at approximately the same time as the main code, causing them to fluctuate between which actually prints out first

Upvotes: 1

Random42
Random42

Reputation: 9159

Since you have not provided any synchronization mechanism, there is no sure way to know which thread is going to be executed first; at different runs, there maybe other order.

Upvotes: 0

Jesper
Jesper

Reputation: 206956

Should not the output be ...

No. Threads run independently of each other. The JVM and operating system decide when which thread is running. In general, the order in which two threads are executed is unpredictable. It could very well happen that when you run the program again, the result is different.

Once the t.start() is done, will it wait for the run() to be executed and then create the second thread?

No, it will not wait. The run() method of the new thread may start immediately, or later, depending on how threads are being scheduled.

Upvotes: 6

Related Questions