本文主要是介绍LinkedBlockingQueue 实现每秒限制N次请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
时间紧迫直接上代码
public class TestA {public static void main(String[] args) {for (int i = 0; i < 100; i++) {new Thread(() -> {while (true) {//执行逻辑TestB.executeTest();}}).start();}}}
import java.util.Random;public class TestB {public static void executeTest() {//获取令牌Token token = TokenQueue.getToken();if (token == null) {System.out.println("=====获取令牌为空!");return;}//执行try {System.out.println("使用token"+token.getName());//随机执行时间1到3000Random random = new Random();int sleep = random.nextInt(3000);//这里要控制时间,如果太长时间没有归还令牌会影响执行效率或阻塞!Thread.sleep(sleep);System.out.println("使用token"+token.getName()+"执行时间"+sleep);} catch (Exception e) {e.printStackTrace();System.out.println("=====位置错误");}finally {//归还令牌TokenQueue.setToken(token);}}}public class Token {private String name;private Long time;public Token(String name, Long time) {this.name = name;this.time = time;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Long getTime() {return time;}public void setTime(Long time) {this.time = time;}
}import java.util.concurrent.LinkedBlockingQueue;public class TokenQueue {//令牌桶private static LinkedBlockingQueue<Token> blockingQueue;static {blockingQueue = new LinkedBlockingQueue<>();blockingQueue.add(new Token("金", System.currentTimeMillis()));blockingQueue.add(new Token("木", System.currentTimeMillis()));blockingQueue.add(new Token("水", System.currentTimeMillis()));blockingQueue.add(new Token("火", System.currentTimeMillis()));blockingQueue.add(new Token("土", System.currentTimeMillis()));}/*** 获取令牌** @return*/public static Token getToken() {try {Token token = blockingQueue.take();//检查是否满足间隔long now = System.currentTimeMillis();long sleepTime = 1000 - (now - token.getTime());if (sleepTime > 1) {System.out.println("获取令牌需要睡眠获取,睡:" + sleepTime);Thread.sleep(sleepTime);}//设置这次token开始使用时间token.setTime(System.currentTimeMillis());return token;} catch (InterruptedException i) {System.out.println("=====获取令牌失败");return null;}}/*** 归还令牌** @return*/public static void setToken(Token token) {try {blockingQueue.put(token);System.out.println("令牌已经归还");} catch (InterruptedException i) {System.out.println("放令牌失败");}}
}
------------------------记录下,灵感源于生活买票。。。。
这篇关于LinkedBlockingQueue 实现每秒限制N次请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!