双十一秒杀架构模型设计
public class TestRateLimiter {
public static void main(String[] args) {
//1秒产生1个令牌
final RateLimiter rateLimiter = RateLimiter.create(1);
for (int i = 0; i < 10; i++) {
//该方法会阻塞线程,直到令牌桶中能取到令牌为止才继续向下执行。
double waitTime= rateLimiter.acquire();
System.out.println("任务执行" + i + "等待时间" + waitTime);
}
System.out.println("执行结束");
}
}
public class TestRateLimiter2 {
public static void main(String[] args) {
final RateLimiter rateLimiter = RateLimiter.create(1);
for (int i = 0; i < 10; i++) {
long timeOut = (long) 0.5;
boolean isValid = rateLimiter.tryAcquire(timeOut, TimeUnit.SECONDS);
System.out.println("任务" + i + "执行是否有效:" + isValid);
if (!isValid) {
continue;
}
System.out.println("任务" + i + "在执行");
}
System.out.println("结束");
}
}
来源:https://www.cnblogs.com/wyq178/p/11261711.html
版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢!
评论