@Component
public class MyRunner implements CommandLineRunner {
private static final int rate = 5;
private volatile static AtomicInteger tokens = new AtomicInteger(0);
public int getTokenValue() {
return tokens.get();
}
@Override
public void run(String... args) throws Exception {
new Thread(() -> {
while(true) {
// 逻辑代码
try {
Thread.sleep(3000); // 模拟工作
int allTokens = tokens.get() + rate;
tokens.set(allTokens);
// System.out.println("输出。。。" + allTokens);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
private final MyRunner myRunner;
@GetMapping("/aaa")
public void aaa() {
int tokenValue = myRunner.getTokenValue();
System.out.println("目前值是:" + tokenValue);
}
注意:
1、@Component,交给spring管理
2、public class MyRunner implements CommandLineRunner
3、private static final int rate = 5,令牌因子
4、private volatile static AtomicInteger tokens = new AtomicInteger(0);
5、public void run(String… args) ,新写run()方法
6、 new Thread(),启动线程进行,匀速生成tokens并赋值
7、新写getTokenValue() ,用于外部获取tokens 值