1

I have been working on a calculator app in Java and I want to implement multithreading for this. I want to start a second thread, to calculate the answer for the given input. The only problem is, the calculation has to return a value and that value need to get displayed, but I don't know how to handle that. (I know its kind of useless to implement multithreading because the calculation doesn't even take a second, but I want to do it as practice and see if its possible)

Here you can see the code for which I want to start a second thread for:

public String calculate() {
//The input (StringBuilder) gets converted to an ArrayList
        String[] tmpArray = inputAsText.toString().split(" ");
        inputAsArrayList = new ArrayList(Arrays.asList(tmpArray));

//Other functions are called to perform calculations on
        inputAsArrayList = calculateFor("x", "÷");
        inputAsArrayList = calculateFor("+", "-");

//The answer gets retrieved from the arrarList and returned as a String
        String answer = String.valueOf(inputAsArrayList.get(0));
        clearInput();
        return answer;
    }

1 Answer 1

1

There are two ways to deal with results from asynchronous code:

  • Wait for the response to become available. This makes the results become available in the current thread.
  • Use some kind of callback mechanism. The results are still not available in the current thread.

The waiting can be done using Future and one of its get methods. For callbacks, I prefer CompletableFuture, with methods like thenAccept. You can even easily hook it into something like the Swing/AWT Event Dispatcher:

future.thenAcceptAsync(action, EventQueue::invokeLater);

This works because the second argument needs to be an Executor, which is a functional interface with one method that takes a Runnable and returns nothing. That's exactly what EventQueue.invokeLater is.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.