Splitting Work into Separate Threads - Java Thread

Java examples for Thread:ThreadPoolExecutor

Introduction

ThreadpoolExecutor can break the tasks into discrete units.

Demo Code

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) throws InterruptedException {

    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    for (int i = 0; i < 10; i++) {
      final int localValue = i;
      queue.add((Runnable) () -> {
        doExpensiveOperation(localValue);
      });/* w w  w  .  ja v  a2  s  .  c o m*/
    }
    ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000,
        TimeUnit.MILLISECONDS, queue);
    executor.prestartAllCoreThreads();
    executor.shutdown();
    executor.awaitTermination(100000, TimeUnit.SECONDS);
  }

  private static void doExpensiveOperation(int index) {
    System.out.println("Starting " + index);
    try {
      Thread.sleep(index * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Ending " + index);
  }
}

Result


Related Tutorials