Reputation: 616
Here is a sample program in java from tutorials point:
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
The output of the program is as follows.
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
I have trouble understanding why the main thread is executing before the child thread. In the program you can see that first new NewThread() is executed. The NewThread class instantiates a new thread and calls the start() function on the new thread which then calls the run() function. The loop in the main function comes only after a new thread is created. However when the program is run , The loop in the main thread is run before the child thread. Please help me understand.
Upvotes: 0
Views: 139
Reputation: 41281
The loop in the main thread is run before the child thread. Please help me understand.
Threads do not have any form of synchronization by default and can run in any order with their executions possibly interleaving. You can acquire locks and use those for ensuring order, for example if the main thread acquires the lock before starting the child thread, having the child thread wait to acquire the lock, and having the main thread release the lock once it's done with its tasks.
Upvotes: 3
Reputation: 272367
Thread.start()
schedules the thread to be run. After that it's up to the JVM (and the OS) to look after the scheduling. How the threads run is determined by a number of factors including the number of CPUs/cores you have, the OS, the priority etc.
If you need the threads to run in a particular order, wait for each other etc., then you have to use the threading tools provided (synchronisation, locks etc.) Otherwise it's completely arbitrary.
Upvotes: 1