下面列出了java.util.concurrent.atomic.AtomicInteger#lazySet() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* get returns the last value lazySet in same thread
*/
public void testGetLazySet() {
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1, ai.get());
ai.lazySet(2);
assertEquals(2, ai.get());
ai.lazySet(-3);
assertEquals(-3, ai.get());
}
/**
* get returns the last value lazySet in same thread
*/
public void testGetLazySet() {
AtomicInteger ai = new AtomicInteger(1);
assertEquals(1, ai.get());
ai.lazySet(2);
assertEquals(2, ai.get());
ai.lazySet(-3);
assertEquals(-3, ai.get());
}
@Test
public void testAtomic() {
AtomicInteger atomicInteger = new AtomicInteger(10);
Assertions.assertThat(atomicInteger.decrementAndGet()).isEqualTo(9); // first decrement and then get
Assertions.assertThat(atomicInteger.getAndDecrement()).isEqualTo(9); // first get and then decrement
Assertions.assertThat(atomicInteger.incrementAndGet()).isEqualTo(9); // first increment and then get
Assertions.assertThat(atomicInteger.getAndIncrement()).isEqualTo(9); // first get and then increment
Assertions.assertThat(atomicInteger.get()).isEqualTo(10); // just get
atomicInteger.set(12); // just set
Assertions.assertThat(atomicInteger.getAndSet(11)).isEqualTo(12); // first get and then set
Assertions.assertThat(atomicInteger.floatValue()).isEqualTo(11); // is equal
Assertions.assertThat(atomicInteger.accumulateAndGet(50, (x, y) -> 2 * x + y)).isEqualTo(72);
// IntBinaryOperator (x, y) -> z . Two times value inside 11 + supplied 50
atomicInteger.set(5);
Assertions.assertThat(atomicInteger.updateAndGet(x -> x * 3)).isEqualTo(15);
// IntUnaryOperator x -> y . Three times value inside 5
Assertions.assertThat(atomicInteger.addAndGet(6)).isEqualTo(21); // add and get
atomicInteger.set(5); // initialize
Assertions.assertThat(atomicInteger.compareAndSet(6, 10)).isFalse(); // will not update 6 != 5
Assertions.assertThat(atomicInteger.compareAndSet(5, 11)).isTrue(); // will update case prev is 5
Assertions.assertThat(atomicInteger.weakCompareAndSet(11, 12)).isTrue();
// ! implementation is same as compareAndSet
atomicInteger.lazySet(10);
Assertions.assertThat(atomicInteger.get()).isEqualTo(10);
AtomicBoolean atomicBoolean = new AtomicBoolean(); // default value=false, getAndSet, [weak]compareAndSet/ [lazy]set
Assertions.assertThat(atomicBoolean.get()).isFalse();
AtomicLong atomicLong = new AtomicLong(); // default value=0
//
AtomicReference<String> reference = new AtomicReference<>("hello");
}
public void sendTrain(final int trainNo) {
final AtomicInteger stationIndex = train[trainNo].stationIndex;
stationIndex.lazySet(stationIndex.get() + 1);
}