Skip to content

Instantly share code, notes, and snippets.

@PSteph
Created May 4, 2020 21:00
Show Gist options
  • Save PSteph/fb681de163462d17a1e686ddd2da2655 to your computer and use it in GitHub Desktop.
Save PSteph/fb681de163462d17a1e686ddd2da2655 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ParallelStream {
public static void main(String... args) {
long start = System.currentTimeMillis();
Stream.generate(Math::random)
.limit(1000)
.parallel()
.forEach(x -> simulationReseau());
double time = (System.currentTimeMillis() - start)/1000.0;
System.out.println(time+" secondes");
// long start = System.currentTimeMillis();
// Stream.generate(Math::random)
// .limit(1000)
// .forEach(x -> simulationReseau());
// double time = (System.currentTimeMillis() - start)/1000.0;
// System.out.println(time+" secondes");
// // Resultat: 11.285 secondes
// Stream normal, l'ordre est conserve
// List<Integer> nombres = Arrays.asList(0,1,2,3,4,5,6,7,8,9);
// nombres.stream().forEach(System.out.print);
// L'ordre est perdu avec les streams parallele
// List<Integer> nombres = Arrays.asList(0,1,2,3,4,5,6,7,8,9);
// nombres.parallelStream().forEach(System.out::print);
// retrouver l'ordre avec forEachOrdered()
List<Integer> nombres = Arrays.asList(0,1,2,3,4,5,6,7,8,9);
nombres.parallelStream().forEachOrdered(System.out::print);
// Resultat: 0123456789
}
public static int simulationReseau(){
try{
Thread.sleep(10);
}catch (InterruptedException e){
// catch exception
}
return 200;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment