Executor And ExecutorService in Java

Category : Java | Sub Category : ExecutorService | By Prasad Bonam Last updated: 2020-11-30 06:22:31 Viewed : 706


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:
BHbArBa
at 2023-11-07 11:06:09
The MEDLINE was searched with the combination of the words guidelines or algorithms with mania, manic, bipolar, manicdepressive or manic depression in order to identify articles with treatment guidelines <a href=https://buycialis.yachts>cheap cialis online canadian pharmacy</a>