Java中的原子操作類 / 併發工具類(Java併發編程的藝術筆記)

等待多線程完成的CountDownLatch

CountDownLatch允許一個或多個線程等待其他線程完成操作,簡單使用如下。

public class Test {
    public static void main(String[] args) throws InterruptedException{
        CountDownLatch clock = new CountDownLatch(2);
         new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("1");
                clock.countDown();
                System.out.println("2");
                clock.countDown();
            }
        }).start();
                 clock.await();
                 System.out.println("3");
    }
}

如果想要等待N個點完成,則在構造方法傳入N。當調用CountDownLatch的countDown方法時,N就會減1,CountDownLatch的await方法 會阻塞當前線程,直到N變成零。此處的N可以是1個線程裏的N個步驟或N個線程。若是用在多線程,只需要把這個CountDownLatch引用傳遞給線程裏。

若等待其他線程很久,不希望讓主線程一直等待,可以使用帶指定時間的await(long time,TimeUnit unit)方法。

 


同步屏障CyclicBarrier

當一組線程到達一個屏障時被阻塞,直至最後一個線程到達屏障時,屏障纔會打開,被攔截的線程才能繼續允許。

它的構造方法是CyclicBarrier(int parties),其參數表示屏障攔截的線程數 量,每個線程調用await方法告訴CyclicBarrier我已經到達了屏障,然後當前線程被阻塞。

此外,它還提供一個更高級的構造函數CyclicBarrier(int parties,Runnable barrierAction),用於在線程到達屏障時,優先執行barrierAction,方便處理更復雜的業務場景。

CyclicBarrier可用於多線程計算數據,最後合併計算結果的場景。如下所示,使用線程池創建4個線程,分別模擬計算每個sheet裏的數據,再由BankWaterService線程彙總4個sheet計算出的結果

public class Test {
    public static class BankWaterService implements Runnable {
//        創建4個屏障,處理完後執行當前類的run方法
        private CyclicBarrier barrier = new CyclicBarrier(4, this);
//        啓動一個用於4個線程的線程池
        private Executor executor = Executors.newFixedThreadPool(4);
        private ConcurrentHashMap<String, Integer>  sheetCount = new ConcurrentHashMap<>();
        private void count() {
            for(int i = 0; i < 4; i++) {
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
//                        計算當前線程的數據,此處將結果省略爲1
                        sheetCount.put(Thread.currentThread().getName(), 1);
                        try {
                            barrier.await();
                        }catch (InterruptedException | BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
        @Override
        public void run() {             // 計算每個線程計算出的結果
                int result = 0;
                for(Map.Entry sheet : sheetCount.entrySet()) {
                    result += (int)(sheet.getValue());
                }
                sheetCount.put("result", result);
            System.out.println(result);
        }
    }
    public static void main(String[] args) throws InterruptedException{
            BankWaterService bankWaterService = new BankWaterService();
            bankWaterService.count();
    }
}

 

CyclicBarrier和CountDownLatch的區別

CountDownLatch的計數器只能使用一次,而CyclicBarrier的計數器可以使用reset()方法重 置。所以CyclicBarrier能處理更爲複雜的業務場景。例如,如果計算髮生錯誤,可以重置計數 器,並讓線程重新執行一次。

CyclicBarrier還提供其他有用的方法,比如getNumberWaiting方法可以獲得Cyclic-Barrier 阻塞的線程數量。isBroken()方法用來了解阻塞的線程是否被中斷。

 


控制併發線程數的Semaphore

Semaphore(信號量)是用來控制同時訪問特定資源的線程數量。

Semaphore可以用於做流量控制,特別是公用資源有限的應用場景,比如數據庫連接假 如有一個需求,要讀取幾萬個文件的數據,因爲都是IO密集型任務,我們可以啓動幾十個線程 併發地讀取,但是如果讀到內存後,還需要存儲到數據庫中,而數據庫的連接數只有10個,這 時我們必須控制只有10個線程同時獲取數據庫連接保存數據,否則會報錯無法獲取數據庫連接。

如下代碼,雖然由30個線程在執行,但只允許10個併發執行。線程通過acquire()方法獲取一個許可證,通過release()歸還許可

public class Test {

    public static void main(String[] args) throws InterruptedException{
            int THREAD_COUNT = 30;
            ExecutorService pool = Executors.newFixedThreadPool(THREAD_COUNT);
            Semaphore s = new Semaphore(10);
            for(int i = 0; i < THREAD_COUNT; i++) {
                pool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            s.acquire();
                            System.out.println("保存數據");
                            s.release();
                        }catch (InterruptedException e) {
                        }

                    }
                });
            }
                    pool.shutdown();
    }
}

 

線程間交換數據的Exchanger

Exchanger用於進行線程間的數據交 換。它提供一個同步點,在這個同步點,兩個線程可以交換彼此的數據。這兩個線程通過 exchange方法交換數據,如果第一個線程先執行exchange()方法,它會一直等待第二個線程也 執行exchange方法,當兩個線程都到達同步點時,這兩個線程就可以交換數據,將本線程生產 出來的數據傳遞給對方。

public class Test {

    public static void main(String[] args) throws InterruptedException{
           Exchanger<String> exc = new Exchanger<>();
           ExecutorService pool = Executors.newFixedThreadPool(2);
           pool.execute(new Runnable() {
               @Override
               public void run() {
                   try {
                       String A = "銀行流水A";
                       exc.exchange(A);
                   }catch (InterruptedException e) { }
               }
           });
           pool.execute(new Runnable() {
               @Override
               public void run() {
                   try {
                       String B = "銀行流水B";
                       String A = exc.exchange("");
                       System.out.println("A數據:" + A );
                   }catch (InterruptedException e) { }
               }
           });
           pool.shutdown();
    }
}

若兩個線程有一個沒有執行行exchange()方法,則會一直等待。若希望避免一直等待,可以使用exchange(V x,longtimeout,TimeUnit unit)設置最大等待時長。

 

 

 


原子操作類概述

java.util.concurrent.atomic包(簡稱Atomic包)中的原子操作類提供了一種線程安全的更新變量的方式,包裏一共提供13個類,分別屬於4中原子更新方式:原子更新基本類型,原子更新數組,原子更新引用和原子更新屬性(字段)。

原子更新基本類型

  • AtomicBoolean:原子更新布爾類型。
  • AtomicInteger:原子更新整型。
  • AtomicLong:原子更新長整型。

3個類提供的方法幾乎一樣,本節以AtomicInteger爲例,它的常用方法如下:

  • int addAndGet(int delta):以原子方式將輸入的數值與實例中的值(AtomicInteger裏的 value)相加,並返回結果。
  • ·boolean compareAndSet(int expect,int update):如果輸入的數值等於預期值,則以原子方 式將該值設置爲輸入的值。
  • ·int getAndIncrement():以原子方式將當前值加1,注意,這裏返回的是自增前的值。
  • ·int getAndSet(int newValue):以原子方式設置爲newValue的值,並返回舊值。

分析以一下getAndIncrement()如何實現原子操作。

public final int getAndIncrement() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
        }
    }
public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

源碼中for循環體的第一步先取得AtomicInteger裏存儲的數值,第二步對AtomicInteger的當 前數值進行加1操作,關鍵的第三步調用compareAndSet方法來進行原子更新操作。

Atomic包只提供了3種基本類型的原子更新,但是Java的基本類型裏還有char、float和double 等,那又如何原子的更新這些類型呢?

Atomic包裏的類基本都是使用Unsafe 實現的,看一下Unsafe的源碼,發現只提供了3種CAS方。,因此對於上述類型,它是先把Boolean轉換成整 型,再使用compareAndSwapInt進行CAS,所以原子更新char、float和double變量也可以用類似的思路來實現。

/**
* 如果當前數值是expected,則原子的將Java變量更新成x
* @return 如果更新成功則返回true
*/
public final native boolean compareAndSwapObject(Object o,long offset,Object expected, Object x);

public final native boolean compareAndSwapInt(Object o, long offset,
int expected, int x);

public final native boolean compareAndSwapLong(Object o, long offset,
long expected, long x);

 


原子更新數組

通過原子的方式更新數組裏的某個元素,Atomic包提供了以下4個類

  • ·AtomicIntegerArray:原子更新整型數組裏的元素。
  • ·AtomicLongArray:原子更新長整型數組裏的元素。
  • ·AtomicReferenceArray:原子更新引用類型數組裏的元素。

AtomicIntegerArray常用方法如下:

  • ·int addAndGet(int i,int delta):以原子方式將輸入值與數組中索引i的元素相加。
  • ·boolean compareAndSet(int i,int expect,int update):如果當前值等於預期值,則以原子方式將數組位置i的元素設置成update值。

數組value通過構造方法傳遞進去,AtomicIntegerArray會將當前數組複製一份,所以當AtomicIntegerArray對內部的數組元素進行修改時,不會影響傳入的數組。

 


原子更新引用類型

原子更新基本類型的AtomicInteger,只能更新一個變量,如果要原子更新多個變量,就需 要使用這個原子更新引用類型提供的類。Atomic包提供了以下3個類

  • ·AtomicReference:原子更新引用類型。
  • ·AtomicReferenceFieldUpdater:原子更新引用類型裏的字段。
  • ·AtomicMarkableReference:原子更新帶有標記位的引用類型。可以原子更新一個布爾類 型的標記位和引用類型。構造方法是AtomicMarkableReference(V initialRef,boolean initialMark)。

AtomicReference的使用示例如下所示:

public class Test {
    public static class User {
        private String name;
        private int agel

        public User(String name, int agel) {
            this.name = name;
            this.agel = agel;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAgel() {
            return agel;
        }

        public void setAgel(int agel) {
            this.agel = agel;
        }
    }

    public static void main(String[] args) throws Exception{
            AtomicReference<User> userRef = new AtomicReference<>();
            User user = new User("conman", 15);
            userRef.set(user);
            User updateUser = new User("new conman", 17);
            userRef.compareAndSet(user, updateUser);
    }
}

 


原子更新字段類

如果需原子地更新某個類裏的某個字段時,就需要使用原子更新字段類,Atomic包提供 了以下3個類進行原子字段更新。 ·AtomicIntegerFieldUpdater:原子更新整型的字段的更新器。

·AtomicLongFieldUpdater:原子更新長整型字段的更新器。

·AtomicStampedReference:原子更新帶有版本號的引用類型。該類將整數值與引用關聯起 來,可用於原子的更新數據和數據的版本號,可以解決使用CAS進行原子更新時可能出現的 ABA問題。

以AstomicIntegerFieldUpdater爲例,每次使用時都必須用靜態方法newUpdater()創建一個更新器並且需要設置想要更新的類和屬性。其次,更新類的字段(屬性)必須使用public volatile修飾符。

public class Test {
    public static class User {
        private String name;
        public volatile int age;        // public volatile

        public User(String name, int agel) {
            this.name = name;
            this.age = agel;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAgel() {
            return age;
        }

        public void setAgel(int agel) {
            this.age = agel;
        }
    }

    public static void main(String[] args) throws Exception{
        // 創建原子更新器,並設置需要更新的對象類和對象的屬性
        AtomicIntegerFieldUpdater<User> userFie = AtomicIntegerFieldUpdater.newUpdater(User.class,
                "age");
        User conan = new User("conan", 10);
//        增加1歲:輸出的是舊值 10
        System.out.println(userFie.getAndIncrement(conan));
        //        輸出新值 11
        System.out.println(userFie.get(conan));
    }
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章