Last active
October 16, 2020 06:54
-
-
Save anton0xf/283a5b84bb1c53620d358246309567c0 to your computer and use it in GitHub Desktop.
OK task 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Надо потокобезопасно выдавать последовательность Фибоначи (начиная со второго элемента): 1, 2, 3, 5, 8, ...