Home / JAVA Complete Reference by Examples / Concurrency / How to use Executors.newCachedThreadPool for Multiple Runnable Tasks in Java 8 by Example
How to use Executors.newCachedThreadPool for Multiple Runnable Tasks in Java 8 by Example
2215 views.
package com.learnbyexamples.concurrency;

import java.math.BigInteger;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Stream;

public class E001_ConcurrencyExecutors {
    public static void main(String[] args) {
        //Create Executor using Executors factory method "newCachedThreadPool"
        //For short live threads
        Executor exec = Executors.newCachedThreadPool();
        
        Runnable task1 = () -> {
            Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE))
                  .limit(5)
                  .forEach(n -> {
                      try {
                        System.out.println("I = "+n.intValue());
                        Thread.sleep(1000);
                      } catch (Exception e) {
                        e.printStackTrace();
                      }
                  });
        };
        
        
        Runnable task2 = () -> {
            Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE))
                  .limit(5)
                  .forEach(n -> {
                      try {
                        System.out.println("J = "+n.intValue());
                        Thread.sleep(1000);
                      } catch (Exception e) {
                        e.printStackTrace();
                      }
                  });
        };
        
        exec.execute(task1);
        exec.execute(task2);
    }
}
Output
I = 1
J = 1
I = 2
J = 2
J = 3
I = 3
J = 4
I = 4
I = 5
J = 5
Related Examples
   How to use Executors.newCachedThreadPool for Multiple Runnable Tasks in Java 8 by Example
Copyright © 2016 Learn by Examples, All rights reserved