java-日常练习-多线程-统计两个线程消耗的时间

场景如下:
我想看下多线程一共消耗了多少时间,请看下这个例子 ,关键是这个类 CommonUtils 里的static 方法。

package a;
class CommonUtils{
    public static  long beginTime1;
    public static  long beginTime2;
    public static  long endTime1;
    public static  long endTime2;

}
class  Test {
    public  int a=0;

    synchronized public void test() throws InterruptedException {
        Thread.sleep(3000);
        a++;
        System.out.println(Thread.currentThread().getName()+"  a的值  "+a);
    }
    }

class RunA extends  Thread{
    Test a;
    public RunA(Test a){
        this.a=a;
    }
    @Override
    public void run() {
        CommonUtils.beginTime1=System.currentTimeMillis();
        super.run();
        try {
            a.test();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        CommonUtils.endTime1=System.currentTimeMillis();
    }
}
class RunB extends  Thread{
    Test a;
    public RunB(Test a){
        this.a=a;
    }
    @Override
    public void run() {
        super.run();
        CommonUtils.beginTime2=System.currentTimeMillis();
        try {
            a.test();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        CommonUtils.endTime2=System.currentTimeMillis();
    }
}
public class Sender extends Thread {

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

    Test a= new Test();
    RunA A=new RunA(a);
    RunB B=new RunB(a);
    A.setName("A");
    A.start();
    B.setName("B");
    B.start();
    Thread.sleep(10000); //主线程等待下多线程运行完
    long begin=CommonUtils.beginTime1;
    if (begin>CommonUtils.beginTime2){
        begin=CommonUtils.beginTime2;
    }
    long end=CommonUtils.endTime1;
    if(end<CommonUtils.endTime2){
        end=CommonUtils.endTime2;
    }

    System.out.println("耗时:"+(end-begin));




    System.out.println("end");

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值