2017-05-05 67 views

回答

1

這裏是做這件事的一種方法:

public class Main { 

    public static void main(String[] args) { 

     DemoApplication app = new DemoApplicationBuilder() 
      .withPassword("mySecretPw") 
      .build(); 

     final Manager<Country> countries =  
      app.getOrThrow(CountryManager.class); 

     ForkJoinPool.commonPool().submit(
      () -> countries.stream().forEach(Main::callback) 
     ); 

    } 

    private static void callback(Country c) { 
     System.out.format("Thread %s consumed %s%n",   
      Thread.currentThread().getName(), c); 
    } 

} 

當然,你可以提供任何流的ForkJoinPool。例如,如果您只希望在回撥中接收名稱以「A」開頭的前十個國家/地區,則可以這樣寫:

ForkJoinPool.commonPool().submit(
    () -> countries.stream() 
     .filter(Country.NAME.startsWith("A")) 
     .limit(10) 
     .forEach(Main::callback) 
);