java.lang.Object
java.util.concurrent.atomic.AtomicBoolean
繼承自Object。
在這個Boolean值的變化的時候不容許在之間插入,保持操做的原子性html
這個方法主要兩個做用 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;之間有了 其餘指令呢 Java代碼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"); } } }
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"); } } }
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"); } } } 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"); } } }