[英]Java with NetBeans 7.2.1 - Execution order issue
考慮 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 核心,那么至少初始部分沒問題,而其他控制消息(Worker 已停止。)仍然是碎片化的。 受到輸出消息的干擾。
使用 Eclipse 執行相同的操作會產生預期的執行順序。
有誰知道這里發生了什么? - 非常感謝您提前提供任何建議!
PS:NetBeans 7.2.1 使用的是 jdk1.7.0_03,Eclipse 版本是 Mars.2 Release (4.5.2) - 甚至在不使用其他方法的情況下將代碼從工作類轉移到主類的主方法時也會出現問題根本不是主要方法。
您正在使用System.out
為您的Worker initialized
並為您Output by Worker...
使用System.err
Output by Worker...
System.out
和System.err
是不同的輸出流,它們在不同的時間被刷新,因此控制台上的輸出是亂序的。
對所有輸出行使用System.out.println()
,所有輸出都將按預期順序排列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.