【问题标题】:Why the order was not guaranteed by Executors.newSingleThreadExecutor()?为什么 Executors.newSingleThreadExecutor() 不能保证顺序?
【发布时间】: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


    【解决方案1】:

    因为 main 方法独立于executorService = Executors.newSingleThreadExecutor();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-03
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2018-08-01
      • 1970-01-01
      相关资源
      最近更新 更多