What is the use of a Thread pool in Java?

前端 未结 7 1973
醉梦人生
醉梦人生 2020-12-04 09:02

What is the use of a Thread pool? Is there a good real world example?

7条回答
  •  感动是毒
    2020-12-04 09:28

    Thread pool is a pool of already created worker thread ready to do the job. It creates Thread and manage them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in form of worker thread.

    Why?

    Because creation of Thread is time consuming process and it delays request processing. It also limits number of clients based upon how many thread per JVM is allowed, which is obviously a limited number.


    Create fixed size thread pool using Executor framework -

    Java 5 introduced a full feature built-in Thread Pool framework commonly known as Executor framework.

    Creating fixed size thread pool using Java 5 Executor framework is pretty easy because of static factory methods provided by Executors class. All you need to do is define your task which you want to execute concurrently and than submit that task to ExecutorService.

    From here, Thread pool will take care of how to execute that task; it can be executed by any free worker thread.

    public class ThreadPoolExample {
        public static void main(String args[]) {
           ExecutorService service = Executors.newFixedThreadPool(10); //create 10 worker threads in Thread Pool
           for (int i =0; i<100; i++){
               service.submit(new Task(i)); //submit that to be done 
           }
        }  
    }
    
    final class Task implements Runnable {
        private int taskId;  
        public Task(int id){
            this.taskId = id;
        }
    
        @Override
        public void run() {
            System.out.println("Task ID : " + this.taskId +" performed by " 
                               + Thread.currentThread().getName());
        }  
    }
    
    Output:
    Task ID : 0 performed by pool-1-thread-1
    Task ID : 3 performed by pool-1-thread-4
    Task ID : 2 performed by pool-1-thread-3
    Task ID : 1 performed by pool-1-thread-2
    Task ID : 5 performed by pool-1-thread-6
    Task ID : 4 performed by pool-1-thread-5
    
    *Output may vary from system to system
    

提交回复
热议问题