场景如下:
我想看下多线程一共消耗了多少时间,请看下这个例子 ,关键是这个类 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");
}
}