Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) throws InterruptedException {
- Last100 s = new Last100();
- for (int i = 0; i < 2000; i++) {
- int bound = 250; // average 150
- if (i > 1000) {
- bound = 550; // average 300
- }
- int time = ThreadLocalRandom.current().nextInt(50, bound);
- System.err.println(s.add(time));
- Thread.sleep(10);
- }
- }
- private static class Last100 {
- private static final int ELEMENTS = 100;
- private int sum;
- private int idx;
- private int[] vals = new int[ELEMENTS];
- private int numOfElements = 0;
- public synchronized int add(int val) {
- int prev = vals[idx];
- vals[idx] = val;
- idx++;
- if (idx == ELEMENTS) {
- idx = 0;
- }
- if (numOfElements < ELEMENTS) {
- numOfElements++;
- }
- sum += val - prev;
- return sum / numOfElements;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement