【发布时间】:2022-11-26 12:36:56
【问题描述】:
我在 Windows 11 x64、IntelliJ IDEA 2022 Ultimate 中使用 JDK/Java 19。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ZooInfo {
public static void main(String[] args) {
ExecutorService executorService = null;
Runnable runnable1 = () -> System.out.println("Printing zoo inventory");
Runnable runnable2 = () -> {
for (int i = 0; i < 3; i++) {
System.out.println("Printing record " + i);
}
};
try {
executorService = Executors.newSingleThreadExecutor();
System.out.println("Begin");
executorService.execute(runnable1);
executorService.execute(runnable2);
executorService.execute(runnable1);
System.out.println("End.");
} finally {
if (executorService != null) {
executorService.shutdown();
}
}
}
}
// Result:
// Begin
// End.
// Printing zoo inventory
// Printing record 0
// Printing record 1
// Printing record 2
// Printing zoo inventory
我读了第 850 页,书 OCP Oracle Certified Professional Java SE 11 Developer - Complete Study Guide),他们说
使用单线程执行器,保证执行结果 顺序地。
为什么
Executors.newSingleThreadExecutor()不保证订单? (“结束”不在控制台结果的行尾。)
【问题讨论】:
标签: java