当我运行以下代码时,8 个可用线程中只有 2 个可以运行,任何人都可以解释为什么会出现这种情况吗?我怎样才能改变代码,使其能够利用所有 8 个线程?
Tree.java:
package il.co.roy;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Tree<T>
{
private final T data;
private final Set<Tree<T>> subTrees;
public Tree(T data, Set<Tree<T>> subTrees)
{
this.data = data;
this.subTrees = subTrees;
}
public Tree(T data)
{
this(data, new HashSet<>());
}
public Tree()
{
this(null);
}
public T getData()
{
return data;
}
public Set<Tree<T>> getSubTrees()
{
return subTrees;
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true; …Run Code Online (Sandbox Code Playgroud) 我发现 Java 并行流有一些令人惊讶的行为。我制作了自己的Spliterator,并且生成的并行流被分割,直到每个流中只有一个元素。这似乎太小了,我想知道我做错了什么。我希望我可以设置一些特征来纠正这个问题。
这是我的测试代码。在Float这里仅仅是一个虚拟的有效载荷,我真正的流类稍微复杂一些。
public static void main( String[] args ) {
TestingSpliterator splits = new TestingSpliterator( 10 );
Stream<Float> test = StreamSupport.stream( splits, true );
double total = test.mapToDouble( Float::doubleValue ).sum();
System.out.println( "Total: " + total );
}
Run Code Online (Sandbox Code Playgroud)
此代码将不断拆分此流,直到每个流Spliterator都只有一个元素。这似乎太多了,效率不高。
输出:
run:
Split on count: 10
Split on count: 5
Split on count: 3
Split on count: 5
Split on count: 2
Split on count: 2
Split on count: 3
Split on count: 2 …Run Code Online (Sandbox Code Playgroud) I am trying to understand the features of Spliterator and came across these 2 methods estimatedSize and getExactSizeIfKnown I could figure out what is estimatedSize but not sure exactly what doesgetExactSizeIfKnowndo. Can someone please give an example explaining the difference between the two.
EDIT: I tried the following example in which both of them are the same. In which cases would they be different?
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(1);
l.add(2);
l.add(3); …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Java 8的parallelStream()并行执行几个长时间运行的请求(例如Web请求).简化示例:
List<Supplier<Result>> myFunctions = Arrays.asList(() -> doWebRequest(), ...)
List<Result> results = myFunctions.parallelStream().map(function -> function.get()).collect(...
Run Code Online (Sandbox Code Playgroud)
因此,如果有两个函数分别阻塞2秒和3秒,我希望在3秒后得到结果.然而,它确实需要5秒钟 - 即似乎函数按顺序执行而不是并行执行.难道我做错了什么?
编辑:这是一个例子.当我想要它〜2000时,花费的时间是~4000毫秒.
long start = System.currentTimeMillis();
Map<String, Supplier<String>> input = new HashMap<String, Supplier<String>>();
input.put("1", () -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "a";
});
input.put("2", () -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "b";
});
Map<String, String> results = input.keySet().parallelStream().collect(Collectors.toConcurrentMap(
key -> key,
key -> {
return input.get(key).get();
}));
System.out.println("Time: " …Run Code Online (Sandbox Code Playgroud)