考虑 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 方法而不使用其他方法时甚至出现问题根本比主要方法。