顺序可以是任意顺序,但是规则的顺序不应更改。同样,对于特定的顺序规则,应该成组出现。
如果是这样,则没有实际并行性的空间。
什么时候
order1-rule1
order1-rule2
order2-rule1
order2-rule2
和
order2-rule1
order2-rule2
order1-rule1
order1-rule2
是2个订单和2条规则的唯一有效运行,
并且
order1-rule1
order2-rule1
order1-rule2
order2-rule2
被认为是无效的,不是并行性,只是order
s的随机化,大概没有增益。如果您一直无所适从order1
,那么可以随机排列列表,仅此而已:
public static void main (String[] args) throws java.lang.Exception
{
List<String> orders = Arrays.asList("order1", "order2", "order3", "order4");
List<String> rules = Arrays.asList("rule1", "rule2", "rule3");
Collections.shuffle(orders);
orders.forEach(order->{
rules.forEach(rule->{
System.out.println(order+"-"+rule);
});
});
}
甚至不需要流,只需两个嵌套循环。测试:https://ideone.com/qI3dqd
order2-rule1
order2-rule2
order2-rule3
order4-rule1
order4-rule2
order4-rule3
order1-rule1
order1-rule2
order1-rule3
order3-rule1
order3-rule2
order3-rule3
原始答案
但是它正在更改rules.forEach(rule-> {}}的顺序。
不,不是的。的order
S可以重叠,但顺序rule
S代表每个顺序被保留。为什么非平行人员还会forEach
做其他事情?
示例代码:
public static void main (String[] args) throws java.lang.Exception
{
List<String> orders = Arrays.asList("order1", "order2", "order3", "order4");
List<String> rules = Arrays.asList("rule1", "rule2", "rule3");
orders.stream().parallel().forEach(order->{
rules.forEach(rule->{
System.out.println(order+"-"+rule);
});
});
}
测试:https : //ideone.com/95Cybg
示例输出:
order2-rule1
order2-rule2
order2-rule3
order1-rule1
order1-rule2
order1-rule3
order4-rule1
order4-rule2
order4-rule3
order3-rule1
order3-rule2
order3-rule3
order
s 的顺序是混合的,但rule
s始终为1-2-3。我认为您的输出只是隐藏了配对(实际上您没有显示它是如何生成的)。
当然,可以将其扩展一些延迟,因此order
s的处理实际上将重叠:
public static void delay(){
try{
Thread.sleep(ThreadLocalRandom.current().nextInt(100,300));
}catch(Exception ex){}
}
public static void main (String[] args) throws java.lang.Exception
{
List<String> orders = Arrays.asList("order1", "order2", "order3", "order4");
List<String> rules = Arrays.asList("rule1", "rule2", "rule3");
orders.stream().parallel().forEach(order->{
rules.forEach(rule->{
delay();
System.out.println(order+"-"+rule);
});
});
}
测试:https : //ideone.com/cSFaqS
示例输出:
order3-rule1
order2-rule1
order2-rule2
order3-rule2
order3-rule3
order2-rule3
order1-rule1
order4-rule1
order1-rule2
order4-rule2
order4-rule3
order1-rule3
这可能是您所看到的,只是没有orderx
一部分。随着order
有形之可以追踪到rule
,使其保持未来1-2-3,每order
。同样,您的示例列表包含order1
两次,这肯定不会帮助您查看正在发生的情况。