Better way to loop in parallel

blackeyedcenter :

If I want to parallelize this code:

try {
    for (int i = 0; i < 10000; i++) {
        new File(String.valueOf(i)).createNewFile();
    }
} catch (IOException e) {
    e.printStackTrace();
}

then I rewrite it to:

ArrayList<String> fileNames = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
    fileNames.add(String.valueOf(i));
}
fileNames.parallelStream().forEach(i -> new File(i).createNewFile());

But isn't there a better (simpler) way for that?

Mushif Ali Nawaz :

Try IntStream in parallel():

IntStream.range(0, 10000).parallel().forEach(i -> {
    try {
        new File(String.valueOf(i)).createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
});

But it won't be much efficient because of the disk operations.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306411&siteId=1