Last active
September 14, 2017 14:05
-
-
Save attacco/a6ed673852b5a1ab7a61bcd1a2d95a3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) { | |
final Stream s1 = Stream.generate(new Supplier<String>() { | |
private final AtomicInteger cnt = new AtomicInteger(); | |
@Override | |
public String get() { | |
sleep(); | |
return "A" + String.valueOf(cnt.incrementAndGet()); | |
} | |
}); | |
final Stream s2 = Stream.generate(new Supplier<String>() { | |
private final AtomicInteger cnt = new AtomicInteger(); | |
@Override | |
public String get() { | |
sleep(); | |
return "B" + String.valueOf(cnt.incrementAndGet()); | |
} | |
}); | |
final Iterator i1 = s1.iterator(); | |
final Iterator i2 = s2.iterator(); | |
StreamSupport.stream(Spliterators.spliteratorUnknownSize( | |
new Iterator<String>() { | |
@Override | |
public boolean hasNext() { | |
final long t1 = System.currentTimeMillis(); | |
final CompletableFuture<Boolean> cf1 = CompletableFuture.supplyAsync(i1::hasNext); | |
final CompletableFuture<Boolean> cf2 = CompletableFuture.supplyAsync(i2::hasNext); | |
CompletableFuture.allOf(cf1, cf2).join(); | |
final boolean has1 = cf1.join(); | |
final boolean has2 = cf2.join(); | |
final long t2 = System.currentTimeMillis(); | |
System.out.println("Wait = " + (t2-t1) + " ms"); | |
return has1 && has2; | |
} | |
@Override | |
public String next() { | |
final Object o1 = i1.next(); | |
final Object o2 = i2.next(); | |
return o1 + "_" + o2; | |
} | |
}, Spliterator.ORDERED | |
), false).forEach(System.out::println); | |
} | |
private static void sleep() { | |
try { | |
Thread.sleep(1_000L); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment