How to Use ExecutorService in Java


In this example, we will use ExecutorService to create a thread pool, and track the progress of the asynchronous tasks with future.

Source Code

package com.beginner.examples;

import java.util.concurrent.*;

public class ExecutorServiceExample {

    public static void main(String[] args){
    	//use ExecutorService to create a thread pool.
    	ExecutorService pool = Executors.newFixedThreadPool(5);
    	for (int j = 0; j < 10; j++) {
    	    final int index = j;
    	    pool.execute(new Runnable() {


    	        @Override
    	        public void run() {
    	            try {
    	                System.out.println(index);
    	                Thread.sleep(3000);
    	            } catch (InterruptedException e) {
    	                // TODO Auto-generated catch block
    	                e.printStackTrace();
    	            }
    	        }
    	    });
    	}
    }
}

Output:

0
1
4
3
2
5
7
6
8
9
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments