我在 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
Run Code Online (Sandbox Code Playgroud)
我读了第 850 页,书 OCP Oracle Certified Professional Java SE 11 Developer - Complete Study Guide),他们说
使用单线程执行器,可以保证结果按顺序执行。
为什么订单没有得到保证Executors.newSingleThreadExecutor()?(“end”不在控制台结果中的行尾。)
shutdownAndAwaitTermination样板文件您忽略了等待执行器服务完成其工作。
\nshutdownAndAwaitTermination您忽略了Javadoc 中显示的方法中提供给您的所有样板代码ExecutorService。
提交对象后,添加对该样板的调用Runnable。现在您的主线程将等待 executor\xe2\x80\x99s 线程完成其任务。
executorService = Executors.newSingleThreadExecutor();\nSystem.out.println("Begin");\nexecutorService.execute(runnable1);\nexecutorService.execute(runnable2);\nexecutorService.execute(runnable1);\nshutdownAndAwaitTermination( executorService ) ; // Block here to wait for executor service to complete its assigned tasks. \nSystem.out.println("End.");\nRun Code Online (Sandbox Code Playgroud)\n您的原始线程碰巧比执行程序服务的线程更早完成其工作。这就是独立线程的本质:不同的线程在不同的时间内完成不同的工作量。
\nLoom 项目致力于为 Java 并发设施带来新功能。
\nJava 19 中正在孵化的结构化并发功能可能会让您更轻松地实现在后台线程上作为一组执行多个任务的目标。
\n