《Java核心技术II》并行流
并行流
从集合中获取并行流:Stream paralleWords = words.parallelStream();
parallel方法将任意顺序流转换为并行流:Stream paralleWords = Stream.of(wordArray).parallel();
以下是不好的示范,假设对字符串的所有短单词计数:
package streams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
public class BadParalleWords {
public static void main(String[] args) throws IOException {
Path path = Path.of("./resources/alice.txt");
var contents = Files.readString(path);
List<String> words = List.of(contents.split("\\PL+"));
var shortWords = new int[12];
words.parallelStream().forEach(
s -> {if(s.length()<12) shortWords[s.length()]++;}
);
System.out.println(Arrays.toString(shortWords));
}
}
结果是多次数据不准确,经典的竞争情况。