user3760100
user3760100

Reputation: 685

Threads in Java,can the stack with main() die/end before the stack with run()?

If I were to write a main class that creates a thread, is it possible that the thread created by the class outlives the main() of the class that created it.

In a way it seems possible because, I could make the newly created thread sleep for an hour , so the new stack goes into blocked state, leaving the original main stack free for execution, the main stack executes and has nothing else to do, while the new stack is still in blocked state.

But on the other hand, there is this statement in Java that everything starts and ends with the main() method.

Please let me know which one is correct

Upvotes: 1

Views: 62

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533520

there is this statement in Java that everything starts and ends with the main() method.

This is not true. You have

import java.io.PrintStream;

class Main {
    static {
        System.out.println("0) Printed before main");
    }

    public static void main(String... args) {
        System.out.println("1) Printed in main");

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                System.out.println("3) Printed long after main");
            }
        });

        throw new RuntimeException() {
            public void printStackTrace(PrintStream ps) {
                System.err.println();
                System.out.println("2) Printed after main");
            }
        };
    }
}

prints

Exception in thread "main" 
0) Printed before main
1) Printed in main
2) Printed after main
3) Printed long after main

Upvotes: 3

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10298

This is not only possible, but the normal state of affairs when you write a Swing app. You're not supposed to create Swing components outside the Swing thread, so the main thread queues up a task to create the UI in the Swing thread and then exits.

Upvotes: 2

David Ehrmann
David Ehrmann

Reputation: 7576

Yes, but only if the thread you create isn't a daemon thread. This (non-daemon) is actually the default.

Upvotes: 5

Related Questions