AtomicBoolean 原子布爾值

AtomicBoolean介紹與使用

java.util.concurrent.atomic.AtomicBooleanhtml

繼承自java.lang.Objectjava

  • 介紹:在這個Boolean值的變化的時候不容許在之間插入,保持操做的原子性
  • 方法和舉例:compareAndSet(boolean expect, boolean update)這個方法主要兩個做用
  1. 比較AtomicBoolean和expect的值,若是一致,執行方法內的語句。其實就是一個if語句
  2. 把AtomicBoolean的值設成update 比較最要的是這兩件事是一鼓作氣的,這兩個動做之間不會被打斷,任何內部或者外部的語句都不可能在兩個動做之間運行。爲多線程的控制提供瞭解決的方案。
// 使用:

private static class BarWorker implements Runnable {  
  
 private static boolean exists = false;  
  
 private String name;  
  
 public BarWorker(String name) {   this.name = name;  }  
  
 public void run() {   
  if (!exists) {    
    exists = true;    
    System.out.println(name + " enter");    
    System.out.println(name + " working");    
    System.out.println(name + " leave");    
    exists = false;   
  } else { 
    System.out.println(name + " give up");   
  }  
 }  
}

 static變量exists用來實現同一時間只有一個worker在工做, 可是假設exists的判斷和exists = true;之間有了其餘指令呢?api

Java代碼多線程

private static class BarWorker implements Runnable {     
    
 private static boolean exists = false;     
    
 private String name;     
    
 public BarWorker(String name) {     
  this.name = name;     
 }     
    
 public void run() {     
  if (!exists) {     
   try {     
    TimeUnit.SECONDS.sleep(1);     
   } catch (InterruptedException e1) {     
    // do nothing     
   }     
   exists = true;     
   System.out.println(name + " enter");     
   try {     
    System.out.println(name + " working");     
    TimeUnit.SECONDS.sleep(2);     
   } catch (InterruptedException e) {     
    // do nothing     
   }     
   System.out.println(name + " leave");     
   exists = false;     
  } else {     
   System.out.println(name + " give up");     
  }     
 }     
    
}

這時輸出是 bar2 enter bar2 working bar1 enter bar1 working bar1 leave bar2 leave 看到兩個線程同時工做了. 這時能夠用AtomicBooleanoracle

Java代碼this

private static class BarWorker implements Runnable {  
  
  private static AtomicBoolean exists = new AtomicBoolean(false);  
  
  private String name;  
  
  public BarWorker(String name) {  
   this.name = name;  
  }  
  
  public void run() {  
   if (exists.compareAndSet(false, true)) {  
    System.out.println(name + " enter");  
    try {  
     System.out.println(name + " working");  
     TimeUnit.SECONDS.sleep(2);  
    } catch (InterruptedException e) {  
     // do nothing  
    }  
    System.out.println(name + " leave");  
    exists.set(false);  
   }else{  
    System.out.println(name + " give up");  
   }  
  }  
  
 }

由於它提供了原子性操做,其中exists.compareAndSet(false, true)這個操做把比較和賦值操做組成了一個原子操做, 中間不會提供可乘之機.輸出爲 bar1 enter bar1 working bar2 give upatom

相關文章
相關標籤/搜索