Advertisement
Guest User

Untitled

a guest
Oct 19th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. public static void main(String[] args) throws InterruptedException {
  2. Last100 s = new Last100();
  3. for (int i = 0; i < 2000; i++) {
  4. int bound = 250; // average 150
  5. if (i > 1000) {
  6. bound = 550; // average 300
  7. }
  8. int time = ThreadLocalRandom.current().nextInt(50, bound);
  9. System.err.println(s.add(time));
  10. Thread.sleep(10);
  11. }
  12. }
  13.  
  14. private static class Last100 {
  15. private static final int ELEMENTS = 100;
  16.  
  17. private int sum;
  18. private int idx;
  19. private int[] vals = new int[ELEMENTS];
  20. private int numOfElements = 0;
  21.  
  22. public synchronized int add(int val) {
  23. int prev = vals[idx];
  24. vals[idx] = val;
  25. idx++;
  26. if (idx == ELEMENTS) {
  27. idx = 0;
  28. }
  29. if (numOfElements < ELEMENTS) {
  30. numOfElements++;
  31. }
  32. sum += val - prev;
  33. return sum / numOfElements;
  34. }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement