多线程判断素数Java代码
时间: 2023-11-06 09:15:46 浏览: 100
以下是判断素数的 Java 代码,可以使用多线程进行优化:
```
import java.util.concurrent.*;
public class PrimeNumberChecker {
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) throws Exception {
int[] numbers = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(threads);
for (int i = 0; i < numbers.length; i++) {
int n = numbers[i];
service.submit(() -> {
if (isPrime(n)) {
System.out.println(n + " is prime");
} else {
System.out.println(n + " is not prime");
}
});
}
service.shutdown();
service.awaitTermination(1, TimeUnit.MINUTES);
}
}
```
这段代码使用了线程池来并发执行素数判断任务,提高了程序的效率。
阅读全文