Submit Runnable to ExecutorService - Java Thread

Java examples for Thread:ExecutorService

Description

Submit Runnable to ExecutorService

Demo Code

package Callable;

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

public class Main {
  public static void main(String[] args) {
    // To execute only single thread at a time
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    // To execute Only two threads at a time
    // ExecutorService executorService = Executors.newFixedThreadPool(2);
    executorService.submit(new A());
    executorService.submit(new A());
    executorService.submit(new A());
//    executorService.submit(()->{for(int i=)});
    System.out.println("Submitted All Three");
    executorService.shutdown();//from   ww  w . j a v a  2  s  .co  m
  }
}

class A implements Runnable {
  @Override
  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(i);
      try {
        Thread.sleep(100);
      } catch (Exception e) {
        System.out.println(e);
      }
    }
  }
}

Related Tutorials