import java.util.Random;
import org.junit.Test;
/**
*
* @author liangjun
* @descriptionTODO 利用回调函数记录方法运行时间,处理异常等
*/
public class CallBackDemo {
@Test
public void testLog() {
final CallBackDemo app = new CallBackDemo();
LogUtil.getInstance().log(new CallBack() {
publicvoid execute() throws InterruptedException {
app.run();
}
});
}
protected void run() throws InterruptedException {
Thread.sleep(new Random().nextInt(2000));
System.out.println("I believe i can fly!");
throw new RuntimeException("抛出运行时异常!");
}
}
/**
*
* @author liangjun
* @descriptionTODO回调函数接口
*/
interface CallBack {
void execute() throws InterruptedException;
}
/**
*
* @author liangjun
* @descriptionTODO 记录方法运行时间;处理异常;
*/
class LogUtil {
private static LogUtil log;
private LogUtil(){
}
public static LogUtil getInstance() {
if(null == log) {
synchronized (LogUtil.class) {
if(null == log) {
log = new LogUtil();
}
}
}
returnlog;
}
publicvoid log (CallBack cb) {
long start = System.currentTimeMillis();
try {
cb.execute();
}catch(Exception e) {
System.out.println(String.format("利用回调函数处理: %s", e.getMessage()));
}
long end = System.currentTimeMillis();
System.out.println(String.format("%s 运行时间: %s ms!", cb.getClass().getName(),(end - start)));
}
}