用Java编写一个测试程序,用多线程计算1万以内素数之和与完全数之和的乘积。
时间: 2024-05-01 13:17:07 浏览: 99
java代码-使用java编写程序打印出N以内的素数的源代码
以下是Java代码:
```java
public class PrimeAndPerfectNumberCalculator implements Runnable {
private long start;
private long end;
private long primeSum;
private long perfectSum;
private Object lock;
public PrimeAndPerfectNumberCalculator(long start, long end, Object lock) {
this.start = start;
this.end = end;
this.lock = lock;
}
private boolean isPrime(long n) {
if (n <= 1) {
return false;
}
for (long i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
private boolean isPerfect(long n) {
long sum = 1;
for (long i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
sum += i;
if (i != n / i) {
sum += n / i;
}
}
}
return sum == n;
}
private void calculate() {
for (long i = start; i <= end; i++) {
if (isPrime(i)) {
synchronized (lock) {
primeSum += i;
}
}
if (isPerfect(i)) {
synchronized (lock) {
perfectSum += i;
}
}
}
}
@Override
public void run() {
calculate();
}
public long getPrimeSum() {
return primeSum;
}
public long getPerfectSum() {
return perfectSum;
}
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
PrimeAndPerfectNumberCalculator calculator1 = new PrimeAndPerfectNumberCalculator(1, 5000, lock);
PrimeAndPerfectNumberCalculator calculator2 = new PrimeAndPerfectNumberCalculator(5001, 10000, lock);
Thread thread1 = new Thread(calculator1);
Thread thread2 = new Thread(calculator2);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
long primeSum = calculator1.getPrimeSum() + calculator2.getPrimeSum();
long perfectSum = calculator1.getPerfectSum() + calculator2.getPerfectSum();
long product = primeSum * perfectSum;
System.out.println("The product of prime sum and perfect sum is " + product);
}
}
```
这个程序创建了两个线程,分别计算1到5000和5001到10000之间的素数和完全数,并且使用锁来保证加和操作的线程安全性。在主线程中,等待两个线程完成计算后,将它们的结果相加,然后计算素数和完全数之和的乘积,并输出结果。
阅读全文