为什么 ExecutorService 等待所有线程完成但 Completablefuture 不等待?
Why does ExecutorService waits for all threads to complete but Completable future not?
在下面的代码中,
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());
}
}
(比)
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));
}
}
}
在第一种情况下,jvm 保持 运行 直到所有线程都完成。但是在第二种情况下,jvm和其他线程在主线程死亡后立即被杀死。
有什么原因吗?
在我看来,'CompletableFuture' 本身不执行任何操作,因此它没有等待线程。它依赖于 运行 个阶段的其他机制。
'runAsync',没有执行器,在其公共 ForkJoin 池中运行任务,documented 具有您观察到的行为。
这并没有回答您 'why' 的问题,只是说它是故意这样设计的。我只能挥手说它的设计者可能认为它是最好的默认选择。
(我同意:在我编写的代码中,如果我到达程序终止点,我想要的是一切都消失。在极少数情况下我需要它完成,我会等待它再退出。)
在下面的代码中,
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());
}
}
(比)
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));
}
}
}
在第一种情况下,jvm 保持 运行 直到所有线程都完成。但是在第二种情况下,jvm和其他线程在主线程死亡后立即被杀死。
有什么原因吗?
在我看来,'CompletableFuture' 本身不执行任何操作,因此它没有等待线程。它依赖于 运行 个阶段的其他机制。
'runAsync',没有执行器,在其公共 ForkJoin 池中运行任务,documented 具有您观察到的行为。
这并没有回答您 'why' 的问题,只是说它是故意这样设计的。我只能挥手说它的设计者可能认为它是最好的默认选择。
(我同意:在我编写的代码中,如果我到达程序终止点,我想要的是一切都消失。在极少数情况下我需要它完成,我会等待它再退出。)