使用jdk的stream, 可以非常方便的將串行改為並行
1, 判斷是否質數
/** * 將一個stream改成簡單的並行 */ @Test public void test1() { // 串行 long count = IntStream.range(0, 100000).filter(this::isPrime).count(); System.out.println(count); // 並行 long count1 = IntStream.range(0, 100000).parallel().filter(this::isPrime).count(); System.out.println(count1); } /** * 判斷是否質數 * @param num * @return */ public Boolean isPrime(int num) { int tmp = num; if (tmp < 2) return false; for (int i = 2; Math.sqrt(tmp) >= i; i++) { if (tmp % i == 0) return false; } return true; }
可以看到, 調用了一個parallel() 就可以改為並行計算
2, 獲取一個集合的並行流
/** * 獲取一個並行流 */ @Test public void test2() { List<JSONObject> objects = Lists.newArrayList(); Stream<JSONObject> jsonObjectStream = objects.parallelStream(); }
3, 使用並行排序
/** * 並行排序 */ @Test public void test3() { int[] lists = new int[1000]; Arrays.parallelSort(lists); }