2013-12-15 39 views
1

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

任何人都可以解釋爲什麼它省略打印?我對併發編程完全陌生。

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

} 

回答

2

你應該等待執行服務調用shutdown

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

後完成我懷疑創建的線程是守護線程,這並不妨礙一個JVM關機。由於線程已被踢掉並被忘記,因此在致電shutdown後,該方法返回,然後JVM退出,因爲沒有其他任何操作了。未完成的工作從未完成。

正如埃利奧特指出的那樣,使用awaitTermination方法:

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