coolguy2000
coolguy2000

Reputation: 27

Return datatype of original method

For example, I have a method which returns a boolean and I'm creating a new thread there, it's hard to return the boolean in the thread.

Let me show you what I mean with this example:

public boolean test() {
    int a = 5;
    int b = 3;

    new Thread(() -> {
        if (a > b) {
            return true; //NOT POSSIBLE
        } else {
            return false;
        }
    }).start();
}

This is just an example. This would not work, I'd need to do something like this:

private boolean value;

public boolean test() {
    int a = 5;
    int b = 3;

    new Thread(() -> {
        if (a > b) {
            value = true;
            return;
        } else {
            value = false;
            return;
        }
    }).start();

    return value;
}

Now my questions, is there a way which is easier than thies? This could get messy if I have more methods like this in a class.

Regards

Upvotes: 1

Views: 65

Answers (2)

user10316011
user10316011

Reputation:

What you want is called futures, look at some examples https://www.baeldung.com/java-future

Or for java 8 and later CompletableFuture https://www.baeldung.com/java-completablefuture , the guide also has an example how to wait for multiple values at once.

Basically you are giving out a promise of a value and the recipient can check whether the background thread has delivered the value already and/or wait until it is done.

Your example might look something like this:

public boolean test() throws Exception {
    int a = 5;
    int b = 3;

    CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() -> {
        if (a > b) {
            return true;
        } else {
            return false;
        }
    });
    return future.get();
}

Upvotes: 6

Koen
Koen

Reputation: 288

When you start a new thread, the current method may complete (return value) before the new thread does.

One way to catch the result is to call, from your new thread, some method of a listener instance (typically the actionPerformed of an ActionListener) which you should pass as a parameter in calling your test()-method.

The basic idea of starting a new thread is to allow some time to pass in a lengthy method while your main program does more pressing things.

Upvotes: 0

Related Questions