Java AtomicBoolean (Java代碼實戰-008)

來源:互聯網
上載者:User

標籤:完成   exec   java代碼   ice   atomic   cti   package   current   結果   

  使用AtomBoolean來實現原子操作

package atomactions;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;/** * Created by xfyou 2018/6/20 16:29. */public class BarWorker implements Runnable {    /**     * <p>     * AtomicBoolean是java.util.concurrent.atomic包下的原子變數,這個包裡面提供了一組原子類。     * <p>     * 其基本的特性就是在多線程環境下,當有多個線程同時執行這些類的執行個體包含的方法時,具有排他性,即當某個線程進入方法,執行其中的指令時,不會被其他線程打斷,而別的線程就像自旋鎖一樣,一直等到該方法執行完成,才由JVM從等待隊列中選擇一個另一個線程進入,這隻是一種邏輯上的理解。     * <p>     * 實際上是藉助硬體的相關指令來實現的,不會阻塞線程(或者說只是在硬體層級上阻塞了)。     * <p>     * 例如AtomicBoolean,在這個Boolean值的變化的時候不允許在之間插入,保持操作的原子性。方法和舉例:compareAndSet(boolean expect, boolean update)。     * 這個方法主要兩個作用     * 1. 比較AtomicBoolean和expect的值,如果一致,執行方法內的語句。其實就是一個if語句     * 2. 把AtomicBoolean的值設成update比較最要的是這兩件事是一氣呵成的,這連個動作之間不會被打斷,任何內部或者外部的語句都不可能在兩個動作之間運行。為多線程的控制提供瞭解決的方案。     */    private static AtomicBoolean exist = new AtomicBoolean(false);    @Override    public void run() {        String name = Thread.currentThread().getName();        if (exist.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");            exist.set(false);        } else {            System.out.println(name + " give up");        }    }    /**     * 僅僅一個線程進行工作,因為exists.compareAndSet(false, true)提供了原子性操作,比較和賦值操作組成了一個原子操作     *     * @param args args     */    public static void main(String[] args) {        BarWorker bw = new BarWorker();        ExecutorService executorService = Executors.newFixedThreadPool(5);        for (int i = 0; i < 5; i++)            executorService.execute(bw);        executorService.shutdown();    }}

 一種可能的輸出結果為:

pool-1-thread-1 enterpool-1-thread-1 workingpool-1-thread-3 give uppool-1-thread-4 give uppool-1-thread-5 give uppool-1-thread-2 give uppool-1-thread-1 leave

 

Java AtomicBoolean (Java代碼實戰-008)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.