Java with NetBeans 7.2.1 - Execution order issue

北城以北 提交于 2019-12-13 22:05:36

问题


Consider the following two classes in a NetBeans Java application. The main class:

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

        Worker worker = new Worker();

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

And a worker class like this:

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");
    }
}

Strangely, the ouput results in the following order:

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

Where it should be:

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

If I set the processor affinity of netbeans to use only one cpu core, then at least the initial part is fine and the other controll message (Worker stopped.) is still fragmented resp. interfered by output messages.

Doing the same thing using Eclipse results in the expected execution order.

Has anyone an idea what is happening here? - Many thanks for any advice in advance!

PS: NetBeans 7.2.1 is using jdk1.7.0_03, Eclipse version is Mars.2 Release (4.5.2) - The issue even appears when shifting the code from the worker class to the main method of the main class without using other methods than the main method at all.


回答1:


You are using System.out for your Worker initialized and System.err for your Output by Worker...

System.out and System.err are different output streams, they are flushed at different times, therefore the output is out of order on console.

Use System.out.println() for all your output lines, all outputs would be in the expected order.



来源:https://stackoverflow.com/questions/36766945/java-with-netbeans-7-2-1-execution-order-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!