Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 小白抛砖引玉一下。
- public class Solution {
- private long lastTime = System.currentTimeMillis();
- private int limitPerSecond;
- private int remains = limitPerSecond;
- public Solution(int permitsPerSecond) {
- this.limitPerSecond = permitsPerSecond;
- }
- public boolean acquire() {
- long curTime = System.currentTimeMillis();
- double timeEplaseInSec = (curTime - lastTime) / 1000.0;
- lastTime = curTime;
- remains += (int)(timeEplaseInSec * limitPerSecond);
- if (remains > limitPerSecond) {
- remains = limitPerSecond;
- }
- if (remains < 1) return false;
- else {
- remains -= 1;
- return true;
- }
- }
- public static void main(String[] args) {
- Solution limiter = new Solution(50);
- while (true) {
- if (limiter.acquire()) {
- // Do something
- } else {
- // wait...
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement