You may need to run a particular task (that can run independently) in parallel fashion in order to improve performance, or lets say, simulate a method call in multi-threaded environment:
Here is a example code snippet to do so:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//prepare task | |
Callable<String> callableTask = () -> { | |
callAMethodHere(); // do you execution here, write to file or call an exiting method etc. | |
return "Tasker"; | |
}; | |
List<Callable<String>> callableTasks = new ArrayList<>(); | |
for(int counnt=0; count < 10 ; count++){ | |
callableTasks.add( callableTask ); | |
} | |
//prepare executor service | |
ExecutorService executorService = Executors.newFixedThreadPool(10); | |
List<Future<String>> futures = executorService.invokeAll(callableTasks); | |
executorService.shutdown(); |