How to use Executors.newCachedThreadPool for Multiple Runnable Tasks in Java 8 by Example
2461 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);
}
}