executors java code example

Example 1: newSingleThreadExecutor

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      ExecutorService executor = Executors.newSingleThreadExecutor();

     	// very simple example, check the website for more info:
     	// https://www.tutorialspoint.com/java_concurrency/concurrency_newsinglethreadexecutor.htm
      	
     executor.submit(new Task());
        System.out.println("Shutdown executor");
        executor.shutdown();
      }
   }

   static class Task implements Runnable {
      
      public void run() {

         try {
            Long duration = (long) (Math.random() * 20);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

Example 2: executors java

ExecutorService executor = Executors.newFixedThreadPool(10);

Tags:

Java Example