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:
-
Should not the output be
InRun Thread-0
Thread-0:
InRun Thread-1
Thread-1:
-
Once the
t.start()is done, will it wait for therun()to be executed and then create the second thread? what if i want to do the followingwhile(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
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.
No, it will not wait. The
run()method of the new thread may start immediately, or later, depending on how threads are being scheduled.