java怎么获取线程的个数_Java多线程—Thread统计完数的个数

import java.math.*;

public class bb extends Thread{

public long start;

public long end;

public long num=0;

public bb(long start,long end)

{

super();

this.start=start;

this.end=end;

}

int isPerfect(int n)

{

int lyy_sum=0;

for(int i = 1; i <=n/2; i++)

if(n%i == 0)

lyy_sum+= i;//统计所有真因子的和。

if(lyy_sum == n)

return 1;//如果与原值相等,则该数为完数。

return 0;//不是完数。

}

//串行算法

public long num()

{

for(long i=start;i<=end;i++)

num+=isPerfect((int)i);

return num;

}

//实现run()

public void run(){

for(long i=start;i<=end;i+=2)

{

num=num+isPerfect((int)i);

}

}

//得到线程的最终结果

public long getNum(){

return num;

}

}

public class aa {

public static void main(String[] args) throws Exception{

bb t1=new bb(1,100000);

bb t2=new bb(2,100000);

long startTime=System.currentTimeMillis();

t1.start();

t2.start();

t1.join();

t2.join();

long endTime=System.currentTimeMillis();

System.out.println("并行结果="+(t1.getNum()+t2.getNum()));

System.out.println("并行时间="+(endTime-startTime));

startTime=System.currentTimeMillis();

bb serial=new bb(1,100000);

long num=serial.num();

endTime=System.currentTimeMillis();

System.out.println("串行结果="+num);

System.out.println("串行时间="+(endTime-startTime));

}

}

运行结果:

363959e9aceb28d12cb47e90a9b9789b.png

分析:

实验加速比为9018/4539=1.987

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值