簡體   English   中英

java System.out丟失了

[英]java System.out missing out

以下簡單代碼的輸出對我來說有點奇怪。 它會錯過一些0到100之間的數字以在控制台上打印。

誰能解釋為什么省略打印? 我對並發編程完全陌生。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;


public class SimpleTest {

    @Test
    public void testSimple() throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for(int i = 0; i <= 100; i++) {
            executorService.execute(new SimpleRunnable(i));
        }

        executorService.shutdown();
    }

}

class SimpleRunnable implements Runnable {

    int i;

    public SimpleRunnable(int i) {
        this.i = i;
    }

    public void run() {
        synchronized(System.out) {
            System.out.println(i);
        }
    }

}

您應該在調用shutdown之后等待執行程序服務完成

executorService.shutdown();
executor.awaitTermination(30, TimeUnit.SECONDS); // Wait for the tasks to finish.
// and flush!
System.out.flush();

我懷疑創建的線程是守護程序線程,它們不會阻止JVM關閉。 由於線程已啟動並被忘記,因此在調用shutdown ,該方法將返回,然后JVM退出,因為沒有其他事情可做。 未完成的工作永遠不會完成。

正如Elliot指出的那樣,請使用awaitTermination方法:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long,java.util.concurrent.TimeUnit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM