Skip to content

Instantly share code, notes, and snippets.

@anton0xf
Last active October 16, 2020 06:54
Show Gist options
  • Save anton0xf/283a5b84bb1c53620d358246309567c0 to your computer and use it in GitHub Desktop.
Save anton0xf/283a5b84bb1c53620d358246309567c0 to your computer and use it in GitHub Desktop.
OK task 1
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FibTest {
private static final Logger LOG = LoggerFactory.getLogger(FibTest.class);
@Test
public void test() {
Fib fib = new Fib();
List<Integer> res = new ArrayList<>();
for (int i = 0; i < 5; i++) {
res.add(fib.next());
}
LOG.info("res: {}", res);
}
static class Fib {
private AtomicReference<Val> ref;
public Fib() {
ref = new AtomicReference<>(new Val(1, 1));
}
public int next() {
Val prev;
Val next;
do {
prev = this.ref.get();
next = prev.next();
} while (!ref.compareAndSet(prev, next));
return this.ref.get().b;
}
}
static class Val {
private final int a;
private final int b;
public Val(int a, int b) {
this.a = a;
this.b = b;
}
public Val next() {
return new Val(b, a + b);
}
}
}
@anton0xf
Copy link
Author

Надо потокобезопасно выдавать последовательность Фибоначи (начиная со второго элемента): 1, 2, 3, 5, 8, ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment