java回调函数

Java代码
public class TestObject {
/**
* 一个用来被测试的方法,进行了一个比较耗时的循环
*/
public static void testMethod(){
for ( int i= 0 ; i< 100000000 ; i++){

}
}
/**
* 一个简单的测试方法执行时间的方法
*/
public void testTime(){
long begin = System.currentTimeMillis(); //测试起始时间
testMethod(); //测试方法
long end = System.currentTimeMillis(); //测试结束时间
System.out.println("[use time]:" + (end - begin)); //打印使用时间
}

public static void main(String[] args) {
TestObject test=new TestObject();
test.testTime();
}
}

public class TestObject {
/**
* 一个用来被测试的方法,进行了一个比较耗时的循环
*/
public static void testMethod(){
for ( int i= 0 ; i< 100000000 ; i++){

}
}
/**
* 一个简单的测试方法执行时间的方法
*/
public void testTime(){
long begin = System.currentTimeMillis(); //测试起始时间
testMethod(); //测试方法
long end = System.currentTimeMillis(); //测试结束时间
System.out.println("[use time]:" + (end - begin)); //打印使用时间
}

public static void main(String[] args) {
TestObject test=new TestObject();
test.testTime();
}
}


大家看到了testTime()方法,就只有"//测试方法"是需要改变的,下面我们来做一个函数实现相同功能但更灵活:

首先定一个回调接口:

Java代码
public interface CallBack {
//执行回调操作的方法
void execute();
}

public interface CallBack {
//执行回调操作的方法
void execute();
}

然后再写一个工具类:
Java代码
public class Tools {

/**
* 测试函数使用时间,通过定义CallBack接口的execute方法
* @param callBack
*/
public void testTime(CallBack callBack) {
long begin = System.currentTimeMillis(); //测试起始时间
callBack.execute(); ///进行回调操作
long end = System.currentTimeMillis(); //测试结束时间
System.out.println("[use time]:" + (end - begin)); //打印使用时间
}

public static void main(String[] args) {
Tools tool = new Tools();
tool.testTime(new CallBack(){
//定义execute方法
public void execute(){
//这里可以加放一个或多个要测试运行时间的方法
TestObject.testMethod();
}
});
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值