![]() |
VOOZH | about |
Executors Manage thread execution. At the top of the executor, hierarchy is the Executor interface, which is used to initiate a thread. ExecutorService Extends Executor and provides methods that manage execution. There are three implementations of ExecutorService: ThreadPoolExecutor, ScheduledThreadPoolExecutor, and ForkJoinPool. java.util.concurrent also defines the Executors utility class, which includes some static methods that simplify the creation of various executors. Related to executors are the Future and Callable interfaces. A Future contains a value that is returned by a thread after it executes. Thus, its value becomes defined βin the future,β when the thread terminates. Callable defines a thread that returns a value. In this article, we are going to learn about Custom ThreadPoolExecutor in java.
First, let us discuss two concepts been aggressively used here namely thread pool and blocking queue.
Also, the important specific methods that are to be implemented are as follows:
Method 1: execute()
This method is contained in the Executor interface. This function executes the given task at some time in the future. It returns nothing hence the return type of this method is void.
Method 2: myNewFixedThreadPool()
This is a factory method of Executors class. It is used to create a fixed number of threads in the thread pool.
Procedure:
Implementation: Here we are passing some threads as 3. The number of tasks is 20 and executing them by using execute method.
Output:
Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1 Current Thread :-> Thread-2 Current Thread :-> Thread-0 Current Thread :-> Thread-1
Note: In the above output, we have printed the thread name as defined in the runnable 20 times as we have submitted 20 tasks which is visually described through a video below