使用stream有序循环效率跟普通循环一样,stream多线程循环效率明显高很多。
import java.util.ArrayList; import java.util.List; import static java.lang.Thread.sleep; public class Test3 { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); List<String> list = new ArrayList<>(1000); int count = 0 ; for (int i = 0; i < 1000; i++) { list.add("a_"+count); count++; } // list.parallelStream().forEach(item -> { list.parallelStream().forEachOrdered(item -> { try { sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("item = " + item); }); /*for (int i = 0; i <list.size() ; i++) { sleep(1); System.out.println("item = " + list.get(i)); }*/ long end = System.currentTimeMillis(); System.out.println("总时间 = " + (end - start)); } }