【问题标题】:Java with NetBeans 7.2.1 - Execution order issueJava with NetBeans 7.2.1 - 执行顺序问题
【发布时间】:2016-08-14 11:57:07
【问题描述】:

考虑 NetBeans Java 应用程序中的以下两个类。主类:

public class ExcecutionOrder {
    public static void main(String[] args) {

        Worker worker = new Worker();

        worker.init();
        worker.doProcessing();
        worker.stop();
    }
}

还有这样的工人阶级:

public class Worker {

    public void init() {
        System.out.println("\n-------------------------------------------------");
        System.out.println("Worker initialized.");
        System.out.println("-------------------------------------------------\n");
    }

    public void doProcessing() {
        printNTimes(2000);
    }

    public void doProcess(int n) {
        printNTimes(n);
    }

    public void printNTimes(int n) {
        System.out.println();
        for (int i = 0; i < n; i++) {
            System.err.println("Output by Worker: " + i);
        }
        System.out.println();
    }

    public void stop() {

        System.out.println("\n-------------------------------------------------");
        System.out.println("Worker stopped.");
        System.out.println("-------------------------------------------------\n");
    }
}

奇怪的是,输出结果如下:

Output from Worker: 0
-------------------------------------------------
Output from Worker: 1
Worker initialized.
Output from Worker: 2
-------------------------------------------------
Output from Worker: 3
[...]

它应该在哪里:

-------------------------------------------------
Worker initialized.
-------------------------------------------------
Output from Worker: 0
Output from Worker: 1
Output from Worker: 3
[...]

如果我将 netbeans 的处理器亲和性设置为仅使用一个 cpu 内核,那么至少初始部分是好的,而另一个控制消息(工人停止。)仍然是碎片化的。受到输出消息的干扰。

使用 Eclipse 执行相同的操作会产生预期的执行顺序。

有人知道这里发生了什么吗? - 非常感谢您提前提供的任何建议!

PS:NetBeans 7.2.1 使用的是 jdk1.7.0_03,Eclipse 版本是 Mars.2 Release (4.5.2) - 将代码从 worker 类转移到 main 类的 main 方法时甚至会出现此问题,而无需完全使用除 main 方法之外的其他方法。

【问题讨论】:

  • 使用带有 jdk1.8.0_05 的 NetBeans IDE 7.4 也可以按预期交付执行顺序。

标签: java order-of-execution io-buffering


【解决方案1】:

您将 System.out 用于您的 Worker initializedSystem.err 用于您的 Output by Worker...

System.outSystem.err 是不同的输出流,它们在不同的时间被刷新,因此控制台上的输出是无序的。

对所有输出行使用System.out.println(),所有输出都将按照预期顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多