Reputation: 413
In the below code, why does the main thread wait until the child thread is finished.
Driver.java
public class Driver {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new ThreadRunner());
t.start();
}
}
ThreadRunner.java
public class ThreadRunner implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Child thread" + i);
}
}
}
Here in the Driver class after calling 't.start()' shouldn't the program quit? I'm not using join but still the main thread waits until the newly spun 'ThreadRunner' run is running. Is it because in java the main thread (which is started by main method) always waits until all the threads are shut?
Upvotes: 1
Views: 162
Reputation: 172
you can add 'System.out.println("main thread");' below 't.start()'
then you can see main thread is the first.
Upvotes: -1
Reputation: 40256
The main thread doesn't actually wait. The main thread completes. The program does not quit because you create a Thread
that is non-daemon. The JVM will shut down when only daemon threads remain.
Upvotes: 2
Reputation: 37950
The main thread exits immediately after having started the other thread, but the Java program as a whole continues running as long as there are non-daemon threads alive (and unless you specifically request it, new threads will be non-daemon).
Making the thread a daemon thread is easy: simply call t.setDaemon(true);
before starting it.
Upvotes: 5