Ta có đoạn code sau:
class NewThread implements Runnable {
Thread t;
NewThread(){
t = new Thread(this, "Demo Thread");
System.out.println("Child Thread: " + t);
t.start();
}
public void run(){
try {
for(int i = 5; i > 0; i--){
System.out.println("Child Thread: " + i);
Thread.sleep(2000);
}
} catch(InterruptedException ex) {
System.out.println("Child Thread Interrupted");
}
System.out.println("Exitting Child Thread...");
}
}
class ThreadDemo{
public static void main(String... a){
new NewThread();
try{
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}catch(InterruptedException ex) {
System.out.println("Main Thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Trong đoạn code trên, tôi đã cố tình để cho thread con sleep 2s sau mỗi lần in ra màn hình. Còn thread main chỉ sleep 1s. Và đây là kết quả:
Như chúng ta thấy, thread main dù đã exit nhưng chương trình vẫn thực hiện tiếp thread con. Chương trình kết thúc khi thread con exit. Javadoc nói về điều này ở đây:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
- The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
- All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.