1 import java.util.ArrayList; 2 import java.util.List; 3 import java.util.Random; 4 5 /** 6 * 多线程计算 7 */ 8 public class ParallelStreamAPI { 9 10 public static void main(String[] args) { 11 12 List<Integer> nums = new ArrayList<>(); 13 Random random = new Random(); 14 for(int i=0; i<10000; i++) nums.add(1000000 + random.nextInt(1000000)); 15 16 long startTime = System.currentTimeMillis(); 17 nums.forEach(n -> {isPrime(n);}); 18 long endTime = System.currentTimeMillis(); 19 System.out.println("耗时:" + (endTime - startTime)); 20 21 22 //使用stream parallelStream 23 startTime = System.currentTimeMillis(); 24 nums.parallelStream().forEach(n -> {isPrime(n);}); 25 endTime = System.currentTimeMillis(); 26 System.out.println("耗时:" + (endTime - startTime)); 27 } 28 29 /** 30 * 判断一个数是不是质素/素数 31 * @param num 32 * @return 33 */ 34 static boolean isPrime(int num) { 35 for(int i=2; i<=num/2; i++) { 36 if(num % i == 0) return false; 37 } 38 return true; 39 } 40 41 }