In this following code,
class MainX {
static void run(int i) {
try {
System.out.println(i + " called");
Thread.sleep(1000);
String s = "";
for (int j = 0; j < 20000; j++) {
s = s + j;
}
System.out.println(i + " completed" + " " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
int p = i;
executorService.submit(() -> MainX.run(p));
}
System.out.println("all called");
executorService.shutdown();
System.out.println("all called" + " Thr:" + Thread.currentThread().getName());
}
}
(Vs)
class MainX {
static void run(int i) {
try {
System.out.println(i + " called");
Thread.sleep(1000);
String s = "";
for (int j = 0; j < 20000; j++) {
s = s + j;
}
System.out.println(i + " completed" + " " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
int p = i;
CompletableFuture.runAsync(() -> MainX.run(p));
}
}
}
In the first case, jvm keeps on running until all the threads are completed. But in the second case, jvm and other threads are killed as soon as main thread dies.
Any reason for this?