Phisc
Phisc

Reputation: 1

threading infinity loop java

Inside a method, I start a thread that waits for user input (swing pushbutton). Only after that input, the thread can be closed and the method returns a value. My problem is that the code waiting for the input is not run inside that thread, but elsewhere:

String returnString = "";
Thread waitThread = new Thread(
                () -> {
                    while (xy == null) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            throw THREAD_INTERRUPTED.toException();
                        }
                    }
                }, "waitThread"
            );

waitThread.start();

try {
    waitThread.join();
} catch (InterruptedException e) {
    throw THREAD_INTERRUPTED.toException();
}

// -> wait for user input -> xy != null -> waitThread ends -> main thread joins -> continue code:

returnString = xy;

return ReturnString;

Why is this necessary? Because the method has to return the value (xy) that is set elsewhere by clicking a pushbutton.

The code above just ends up in an infinity loop, not allowing any interaction with the swing components.

Not being a pro in swing, I suppose the main thread is meant to catch interaction events. Since it is stuck in the waitThread.join(); , thats not possible. Correct?

Is there a way to restructure this?

Upvotes: 0

Views: 161

Answers (3)

jannis
jannis

Reputation: 5210

To answer jannis' question: The method opens a popup window that holds lets say two buttons. Each button sets a specific return value for the popup, which is then returned by the same method. So the method needs to open and close the popup. I know this is stupid, but it has to be this way. The setup would work, if I could keep interaction with the frontend enabled while waiting somehow.

Judging from this comment you seem to be trying to rediscover what is called a "modal dialog" and it's not stupid, at all. Please see the official documentation about dialogs in Swing: How to Make Dialogs .

Upvotes: 0

ryvantage
ryvantage

Reputation: 13486

Why reinvent the wheel? Plenty of ways to do this out-of-the-box:

public static void main(String[] args) {
    String message = JOptionPane.showInputDialog("What are you gonna tell me?");
    System.out.println(message);
}

JOptionPane

Upvotes: 1

GhostCat
GhostCat

Reputation: 140457

I think you are going down the wrong route.

Clicking a button leads to an event, and then there should be an ActionListener reacting to that.

And that listener could update some "statish" thingy, and your other thread is reading that information.

Upvotes: 0

Related Questions