0

I am trying to learn ExecutorService interface and its methods. I created an object of type ExecutorService using Executors class static method newFixedThreadPool() and trying to call the execute() method of ExecutorService interface.


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

class WorkerThread implements Runnable {
    private String message;

    public WorkerThread(String s) {
        this.message = s;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + " (Start) message = " + message);

        System.out.println(Thread.currentThread().getName() + " (End)");// prints thread name
    }

}

public class TestThreadPool {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);// creating a pool of 5 threads
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);// calling execute method of ExecutorService
        }
        
        executor.shutdown();
        while (!executor.isTerminated()) {
        }

        System.out.println("Finished all threads");
    }
}

In above code, I have created an object of type ExecutorService using Executors class newFixedThreadPool method which creates a pool of 5 threads.

But How executor is calling execute() method here, as it is an abstract method of ExecutorService interface and the Executors class also don't have any execute() method?

Mayank Kumar Thakur
  • 588
  • 1
  • 8
  • 23
  • 1
    Why are you passing a `Thread` to an `ExecutorService`? – Boris the Spider Sep 09 '21 at 20:41
  • Your class name `WorkerThread` is misleading. Do not think about your work in terms of threads. The point of the Executors framework is to relieve you of the burden of juggling threads. Think of *tasks* that need to be executed, defined as `Runnable` or `Callable` objects. Submit them to an object of type `ExecutorService`. Understand that `ExecutorService` is an *interface*. Use `Executors` utility class to get a *concrete implementation* of that interface. Generally we do not care what particular concrete class is involved; we only care that it offers the methods promised by the interface. – Basil Bourque Sep 09 '21 at 21:08

0 Answers0