سؤال

I know that this question sounds silly - I think that lambdas are execute in parallel, so when I run something like

List<Integer> list = ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(1);
list.forEach(n -> System.out.println(""+n));

I woud not get "3\n2\n1\n" every time. I tried to make some kind of sleep() inside the closure, but it looks like that sleep the thread above, not each lambda execution. (Something like n -> { sleep(n*1000); System.out.println(""+n)}) Can this be done anyhow? Or am I wrong because some parallel stream, etc., should be used instead ordinaly not concurent list? Or is my idea totaly wrong?

هل كانت مفيدة؟

المحلول

forEach applied to an Iterable is generally executed sequentially. If you want parallel execution you need to create a parallel stream: list.parallelStream().forEach(...).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top