java.util.concurrent.atomic.AtomicBooleanhtml
繼承自java.lang.Objectjava
// 使用: 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