Skip to content
Advertisement

How to run 2 methods concurrently in same class with Java

I would like to use 2 methods in the same class concurrently using the same object in Java. For example:

JavaScript

And using this methods in another method:

JavaScript

note: They don’t have to be synchronized.

Advertisement

Answer

There are several ways to achieve your task. You have quiet easy situation when threads should not be synchronized.

You can use ExecutorService from Java Concurrency:

JavaScript

Remember to shutdown ExecutorService otherwise your application won’t stop because it will have alive threads.

Or you can have the simplest approach using vanilla Java threads:

JavaScript

To get computation results you can get the Future<Integer> from executorService and then you have a choice:

  • poll Future if it is done
  • wait until the Future will be completed.
  • wait explicitly for a certain timeout

Here is an example:

JavaScript

Note, while we are explicitly waiting for result of future1, future2 is still being executed in another thread. It means that there won’t be big delay in computation of future2 in particularly this example.

Also, take a look at CompletionStage which is used in asynchronous computations.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement