在完整的名字中如何工作?
主函数仅输出1、2和3。为什么在thenrun中运行的运行不运行和打印4?
import java.util.concurrent.CompletableFuture;
import java.lang.Thread;
class CF {
static void doSomething() {
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println("ggwp");
}
}
static CompletableFuture<Void> printAsync(int i) {
return CompletableFuture.runAsync(() -> {
doSomething();
System.out.print(i);
System.out.println(Thread.currentThread().getName());
});
}
public static void main(String[] args) {
printAsync(1).join();
CompletableFuture.allOf(printAsync(2), printAsync(3))
.thenRun(() -> printAsync(4));
doSomething();
}
}
但是,当我更改如下所示的滴定功能时,将打印所有数字1,2,3和4。
static void doSomething() {
return;
}
The main function outputs only 1, 2 and 3. Why does the Runnable in thenRun not run and print 4 as well?
import java.util.concurrent.CompletableFuture;
import java.lang.Thread;
class CF {
static void doSomething() {
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println("ggwp");
}
}
static CompletableFuture<Void> printAsync(int i) {
return CompletableFuture.runAsync(() -> {
doSomething();
System.out.print(i);
System.out.println(Thread.currentThread().getName());
});
}
public static void main(String[] args) {
printAsync(1).join();
CompletableFuture.allOf(printAsync(2), printAsync(3))
.thenRun(() -> printAsync(4));
doSomething();
}
}
However, when I change the doSomething function as shown below, all the numbers 1,2,3 and 4 will be printed.
static void doSomething() {
return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是从
printAsync()
调用dosomething()
,每个调用将调用线程的睡眠时间为100ms。因此,您不会等待足够长的时间来查看4
的输出。您可以按照注释中建议的
加入
等待,直到所有提交的任务完成。或(为了帮助了解正在发生的事情),您可以将参数添加到dosomething
以指定MS睡眠的数量并在主线程中等待更长的时间,如下所示。并不是没有执行
printasync(4)
。相反,JVM终止该过程,因为所有非daemon线程(在这种情况下,主线程)都是在此之前完成的。You invoke
doSomething()
fromprintAsync()
and each invocation puts the invoking thread to sleep for 100ms. Therefore you don't wait long enough to see the output of4
.You can use
join
as suggested in the comments to wait until all submitted tasks are finished. Or (to help understand what is happening) you can add a parameter todoSomething
to specify the amount of ms to sleep and wait a bit longer in your main thread, as shown below.It is not that the
printAsync(4)
is not executed. Rather, the jvm terminates the process because all non-daemon threads (in this case the main thread) are done before that point.如注释中所述,
.thenrun(() - &gt; printAsync(4).join())。join();
将创建另一个plote
ploteablefuture
并完成它,给您预期的输出。As mentioned in the comments,
.thenRun(() -> printAsync(4).join()).join();
will create anotherCompletableFuture
and complete it, giving you the expected output.