September 2020 - CodeByAkram

Multi threading using Executor Services in Java

 The ExecutorService interface, executes tasks in parallel in background and represents an asynchronous execution mechanism. The ExecutorService create and maintain the reusable thread pool.


How to create ExecutorService?

To create ExecutorService, you can use Executors factory to create the instance of ExecutorService. Lets see some examples.


 There are diffrent way to execute or submit the task with ExecutorService.
  1. submit(Runnable)
  2. submit(Callable)
  3. execute(Runnable)
  4. invokeAny(...)
  5. invokeAll(...)
Lets go through with the example to run multiple treads with ExecutorService.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HTMLUnitMultipleThreads {

	public static void main(String[] args) {

		int threadSize = 5;
		ExecutorService executor = Executors.newFixedThreadPool(threadSize);
		for (int i = 0; i < threadSize; i++) {
			executor.submit(new MultiThreadingService());
		}
	}
}

public class MultiThreadingService implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread Name = " + Thread.currentThread().getName());
		}

	}

}