How to start a background thread that doesn't block the main thread in Java?
Asked Answered
K

2

6

I have the following Java code:

public static void main(String[] args)
{
    new Thread(new MyRunnable()).run();
    showGUI();
}

My problem is that starting MyRunnable blocks the main thread, causing showGUI to not be called until it finishes running. What I'd like the program to do is spawn MyRunnable and allow it to run independently in the background, enabling the main thread to forget about it and go ahead and do what it wants (like call showGUI).

Kaplan answered 21/4, 2012 at 6:42 Comment(0)
S
18

run executes on the main thread. start will create a new thread execution and execute it's run method on that thread.

Symptomatic answered 21/4, 2012 at 6:45 Comment(0)
S
12

You should call method start() on thread, not run().

Sisson answered 21/4, 2012 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.