Given the two examples below, what happens if they are compiled and executed?

Example №1:

public class Main {
    public static void main(String[] args) {
        new Thread(){
            { this.setDaemon(true); }

            public void run() {
                while(true) {
                    System.out.println("Thread is running!");
                }
            }
        }.start();
    }
}
Example №2:

public class Main {
    public static void main(String[] args) {
        new Thread() {

            public void run() {
                while(true) {
                    System.out.println("Thread is running!");
                }
            }
        }.start();
    }
}
Explanation
Example №1:
The created thread will be of a Daemon type, which means that it will be stopped once the main application ends.
Example №2:
The second example, creates non-Daemon thread, hence it will be executed until its run() method ends, it's while(true) statement invoking an endless loop.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes