Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.
To invoke this function using an ExecutorService (similar to a goroutine in Go), use:
You can also start a thread for an anonymous function call.
Our two function calls are running asynchronously in separate threads now. Wait for them to finish (for a more robust approach, you might use more advanced synchronization techniques).
When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads’ output may be interleaved, because they are being run concurrently by the Java runtime.
Next, we’ll look at a complement to threads in concurrent Java programs: Future and CompletableFuture.