Executor And ExecutorService in Java

Category : Java | Sub Category : ExecutorService | By Runner Dev Last updated: 2020-11-30 11:52:31 Viewed : 213


1. Executor And ExecutorService in Java With Examples

It gives an overview of Java Executors framework -

1.           Executor interfaces- Executor, ExecutorService and ScheduledExecutorService interfaces which define the three executor object types.

2.           Thread pools- Executor implementation classes like ThreadPoolExecutor and ScheduledThreadPoolExecutor which use thread pools.

 

2.  Example:

ExecutorDemo.java

   

 package runnerdev;

 

import java.util.concurrent.Executors;

import java.util.concurrent.ExecutorService;

 

public class ExecutorDemo {

 

     public static void main(String[] args) {

         // creating executor with pool of 3 threads

         ExecutorService ex = Executors.newFixedThreadPool(3);

         // running 10 tasks

         ex.execute(new Task());    

         ex.execute(new Task());

         ex.execute(new Task());

         ex.execute(new Task());

         ex.execute(new Task());

         ex.execute(new Task());

         ex.execute(new Task());

         ex.execute(new Task());

         ex.execute(new Task());

         ex.execute(new Task());

        

         // shutting down the executor service

         ex.shutdown();

     }

}

 

class Task implements Runnable {

 

     @Override

     public void run() {

         System.out.println("in run task for thread - " + Thread.currentThread().getName());

         try {

              Thread.sleep(500);

         } catch (InterruptedException e) {

              e.printStackTrace();

         }

     }

 

}

 Output:

in run task for thread - pool-1-thread-3

in run task for thread - pool-1-thread-1

in run task for thread - pool-1-thread-2

in run task for thread - pool-1-thread-2

in run task for thread - pool-1-thread-1

in run task for thread - pool-1-thread-3

in run task for thread - pool-1-thread-1

in run task for thread - pool-1-thread-2

in run task for thread - pool-1-thread-3

in run task for thread - pool-1-thread-1


Search
Related Articles

Leave a Comment:
Jurrics
at 2022-05-14 14:01:42
https://newfasttadalafil.com/ - buy generic cialis online thrill <a href=https://newfasttadalafil.com/>Cialis</a> tadalafil fourm https://newfasttadalafil.com/ - Cialis Lqzeaj Canadian Cialas Without