Advertisement
absolute100

Untitled

Jun 20th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. 小白抛砖引玉一下。
  2. public class Solution {
  3.     private long lastTime = System.currentTimeMillis();
  4.     private int limitPerSecond;
  5.     private int remains = limitPerSecond;
  6.    
  7.     public Solution(int permitsPerSecond) {
  8.         this.limitPerSecond = permitsPerSecond;
  9.     }
  10.    
  11.     public boolean acquire() {
  12.         long curTime = System.currentTimeMillis();
  13.         double timeEplaseInSec = (curTime - lastTime) / 1000.0;
  14.         lastTime = curTime;
  15.         remains += (int)(timeEplaseInSec * limitPerSecond);
  16.         if (remains > limitPerSecond) {
  17.             remains = limitPerSecond;
  18.         }
  19.         if (remains < 1) return false;
  20.         else {
  21.             remains -= 1;
  22.             return true;
  23.         }
  24.     }
  25.    
  26.     public static void main(String[] args) {
  27.         Solution limiter = new Solution(50);
  28.         while (true) {
  29.             if (limiter.acquire()) {
  30.                 // Do something
  31.             } else {
  32.                 // wait...
  33.             }
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement