AtomicBoolean相关API

AtomicBoolean和AtomicInteger实现方式相同,AtomicBoolean默认是false

private volatile int value;

/**
 * Creates a new {@code AtomicBoolean} with the given initial value.
 *
 * @param initialValue the initial value
 */
public AtomicBoolean(boolean initialValue) {
     
    value = initialValue ? 1 : 0;
}

AtomicBoolean相关的几个API

class AtomicBooleanTestTest {
     

  /**
   * 默认值是false
   */
  @Test
  public void testCreate() {
     
    AtomicBoolean atomicBoolean = new AtomicBoolean();
    assertFalse(atomicBoolean.get());
    System.out.println(atomicBoolean.get());
  }

  @Test
  public void testCreateWithParam() {
     
    AtomicBoolean atomicBoolean = new AtomicBoolean(true);
    System.out.println(atomicBoolean.get());
  }
  
  @Test
  public void testGetAndSet() {
     
    AtomicBoolean bool = new AtomicBoolean(true);
    final boolean result = bool.getAndSet(false);
    assertTrue(result);
    assertFalse(bool.get());
  }
  
  @Test
  public void testCAS() {
     
    // 当前的value是false 默认值是false
    AtomicBoolean bool = new AtomicBoolean();
    final boolean b = bool.compareAndSet(false, true);
    assertTrue(b);
    System.out.println(b);
  }
}

boolean类型在多线程中是不安全的,多线程中需要使用AtomicBoolean

你可能感兴趣的:(多线程)