import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* 参考链接: <a href="https://www.runoob.com/w3cnote/java-annotation.html">菜鸟教程注解的使用</a><br/>
* 第一步: 定义一个注解
*/
@Documented
@Inherited
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@interface Statistics {
}
/**
* volatile关键字解析: <a href="https://www.cnblogs.com/dolphin0520/p/3920373.html">https://www.cnblogs.com/dolphin0520/p/3920373.html</a><br/>
* 第二步: 定义一个类,使用该注解
*/
class RandomNum {
@Statistics
public static volatile Integer randomNum = 0;
public void setRandomNum(Integer randomNum) {
RandomNum.randomNum = randomNum;
}
public Integer getRandomNum() {
return randomNum;
}
}
/**
* 参考链接: <a href="https://www.cnblogs.com/mzdljgz/p/11629898.html">反射中对注解的简单解析</a><br/>
* 定义一个类,对上述类进行解析,这里通过反射将被标记注解的参数的值获取。
*/
class Trace {
public Trace() throws ClassNotFoundException {
Class<?> clazz = Class.forName(RandomNum.class.getName());
Field[] fields = clazz.getFields();
try {
for (Field field : fields) {
if (field.isAnnotationPresent(Statistics.class)) {
Object object = field.get(clazz);
System.out.println("记录日志: " + field.getName() + ":" + object);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 定时器基础:<a href="https://www.cnblogs.com/fnlingnzb-learner/p/6024095.html">https://www.cnblogs.com/fnlingnzb-learner/p/6024095.html</a><br/>
* 主类,定义两个线程,一个是定时器,一个是普通线程。定时器进行记录值,线程进行写入值。
*/
public class Main {
public static void main(String[] args) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
try {
new Trace();
} catch (Exception e) {
e.printStackTrace();
}
}
}, 200, 300);
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
new RandomNum().setRandomNum(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}