题目
编写一个测试程序,用多线程计算1万以内素数之和与完全数之和的乘积。
这道题我写的比较水,创建了三个线程,一个计算素数和,一个计算完全数的和,然后一个相乘,具体实现如下
package thread;
class thread1 extends Thread {
long sum = 0;
private static boolean isPrime(int src) {
double n = Math.sqrt(src);
if (src < 2) {
return false;
}
if (src == 2 || src == 3) {
return true;
}
if (src % 2 == 0) {// 先判断是否为偶数,若偶数就直接结束程序
return false;
}
for (int i = 3; i <= n; i += 2) {
if (src % i == 0) {
return false;
}
}
return true;
}
public void run() {
for (int i = 1; i <= 10000; i++) {
if (isPrime(i) == true) {
sum += i;
}
}
System.out.println("素数之和:" + sum);
}
}
class thread2 extends Thread {
long count=0;
public static boolean isWanshu(int num){
long ssc=0;
for(int i=1;i<num;i++){
if(num%i==0){
ssc=ssc+i;
}
}
if(ssc==num){
return true;
}else{
return false;
}
}
public void run() {
for (int i = 1; i <= 10000; i++) {
if (isWanshu(i) == true) {
count += i;
}
}
System.out.println("完全数之和:" + count);
}
}
class thread3 extends Thread {
long a=0;
long b=0;
private static boolean isPrime(int src) {
double n = Math.sqrt(src);
if (src < 2) {
return false;
}
if (src == 2 || src == 3) {
return true;
}
if (src % 2 == 0) {// 先判断是否为偶数,若偶数就直接结束程序
return false;
}
for (int i = 3; i <= n; i += 2) {
if (src % i == 0) {
return false;
}
}
return true;
}
public static boolean isWanshu(int num){
long ssc=0;
for(int i=1;i<num;i++){
if(num%i==0){
ssc=ssc+i;
}
}
if(ssc==num){
return true;
}else{
return false;
}
}
public void run() {
for (int i = 1; i <= 10000; i++) {
if (isPrime(i) == true) {
b += i;
}
}
for (int i = 1; i <= 10000; i++) {
if (isWanshu(i) == true) {
a += i;
}
}
System.out.println("乘积为:"+a*b);
}
}
class Main {
public static void main(String args[]){
thread1 threadA = new thread1();
thread2 threadB = new thread2();
thread3 threadC = new thread3();
threadA.start();
threadB.start();
threadC.start();
}
}