【项目说明】:继承Thread类实现求九位自幂数个数的Java多线程并行程序
求九位自幂数个数并输出结果、串行、并行时间、以及加速比。
【项目代码】:
/**继承Thread类实现求九位自幂数个数的Java多线程并行程序*/
public class And extends Thread {
private long start;
private long sum=0;
public And(long start) {
super();
this.start = start;
}
public void run() {
long a,b,c,d,e,f,g,h;
for( a=start; a<=9; a+=2)
for( b=0; b<=9; b++)
for(c=0; c<=9; c++)
for(d=0; d<=9; d++)
for(e=0; e<=9; e++)
for(f=0; f<=9; f++)
for(g=0; g<=9; g++)
for(h=0; h<=9; h++)
if(a*10000000+b*1000000+c*100000+d*10000+e*1000+f*100+g*10+h==a*a*a*a*a*a*a*a+b*b*b*b*b*b*b*b+c*c*c*c*c*c*c*c+d*d*d*d*d*d*d*d+e*e*e*e*e*e*e*e+f*f*f*f*f*f*f*f+g*g*g*g*g*g*g*g+h*h*h*h*h*h*h*h)
sum++;
}
public long sum(){
long a,b,c,d,e,f,g,h;
for( a=start; a<=9; a++)
for( b=0; b<=9; b++)
for(c=0; c<=9; c++)
for(d=0; d<=9; d++)
for(e=0; e<=9; e++)
for(f=0; f<=9; f++)
for(g=0; g<=9; g++)
for(h=0; h<=9; h++)
if(a*10000000+b*1000000+c*100000+d*10000+e*1000+f*100+g*10+h==a*a*a*a*a*a*a*a+b*b*b*b*b*b*b*b+c*c*c*c*c*c*c*c+d*d*d*d*d*d*d*d+e*e*e*e*e*e*e*e+f*f*f*f*f*f*f*f+g*g*g*g*g*g*g*g+h*h*h*h*h*h*h*h)
sum++;
return sum;
}
public long getSum() {
return sum;
}
public static void main(String[] args) throws InterruptedException {
And thread1=new And(1);
And thread2=new And(2);
long startTime=System.currentTimeMillis();
thread1.start();
thread2.start();
thread1.join();
thread2.join();
long endTime=System.currentTimeMillis();
System.out.println("并行结果="+(thread1.getSum()+thread2.getSum()));
System.out.println("并行时间="+(endTime-startTime));
long t1=endTime-startTime;
startTime=System.currentTimeMillis();
And serial=new And(1);
long sum=serial.sum();
endTime=System.currentTimeMillis();
System.out.println("串行结果="+sum);
System.out.println("串行时间="+(endTime-startTime));
long t2=endTime-startTime;
System.out.println("加速比="+t2*1.0/t1);
}
}
【运行截图】: