2017-05-05 37 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) 
);