并發(fā)編程藝術(shù)-8

本文主要介紹的是Java 并發(fā)編程的里面幾個工具類: CountDownLatch, CyclicBarrier, Semaphore, Exchanger, 分析以及使用介紹。

(1) CountDownLatch 類用一個繼承了AQS 抽象類作為內(nèi)部類,實現(xiàn)了讓一個線程或者多個線程等待到達到某一個條件狸页,源碼里面使用State 來記錄考廉,當state 等于 0 時掏膏,所有等待線程都被釋放拜轨。

A code CountDownLatch is a versatile synchronization tool and can be used for a number of purposes. A
CountDownLatch initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await wait at the gate until it is opened by a thread invoking countDown. A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

Example :

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 
 * @author Eric
 *
 */
public class CountDownLatchUsage {

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch latch = new CountDownLatch(2);

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("This is the thread one");

            }

        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("This is the thread Two");

            }

        }).start();

        System.out.println("Going to release the latch");
        latch.countDown();//state = 1
        TimeUnit.SECONDS.sleep(10);
        latch.countDown();//state = 0

        System.out.println("The end");

    }

}

(2) CyclicBarrier 用于一些線程等待其他線程到達同一個柵欄點盯拱,最后一個線程到達之前弥喉,所有的線程都被阻塞郁竟,而且所有等待線程釋放后,CyclicBarrier 可以被復用由境。

Example :

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierUsage {

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {

        CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {

            @Override
            public void run() {
                System.out.println("Let's go!!!");

            }
        });

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("Thread 1 is waiting");
                try {
                    barrier.await();
                    System.out.println("Thread 1 is running");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {

                System.out.println("Thread 2 is waiting");
                try {
                    barrier.await();
                    System.out.println("Thread 2 is running");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        }).start();

        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
    }

}

(3) Semaphore 用來維護一系列許可證棚亩,經(jīng)常用來限制線程的數(shù)目蓖议,用于資源的訪問,同樣在內(nèi)部有一個繼承了AQS的Sync讥蟆,用于公平NonfairSync和FairSync,兩者的區(qū)別是

公平鎖(首先檢查等待隊列中是否已有線程在等待)

protected int tryAcquireShared(int acquires) {
            for (;;) {
                if (hasQueuedPredecessors())
                    return -1;
                int available = getState();
                int remaining = available - acquires;
                if (remaining < 0 ||
                    compareAndSetState(available, remaining))
                    return remaining;
            }
        }

非公平鎖: 直接檢查是否能獲取許可勒虾,可以的話直接運行,否者進入等待隊列瘸彤。

        final int nonfairTryAcquireShared(int acquires) {
            for (;;) {
                int available = getState();
                int remaining = available - acquires;
                if (remaining < 0 ||
                    compareAndSetState(available, remaining))
                    return remaining;
            }
        }

Example :

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreUsage {

    public static void main(String[] args) {
        Semaphore sem = new Semaphore(2, true);
        
        
        new Thread(new Runnable(){

            @Override
            public void run() {
                
                try {
                    sem.acquire(1);
                    System.out.println("This is Thread 1, get the permit");
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    sem.release();
                }
                
                System.out.println("This is Thread 1");
            }
            
        }).start();
        
        new Thread(new Runnable(){

            @Override
            public void run() {

                
                try {
                    sem.acquire(1);
                    System.out.println("This is Thread 2, get the permit");
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    sem.release();
                }
                
                System.out.println("This is Thread 2");
                
            
            }
            
        }).start();
        
        new Thread(new Runnable(){

            @Override
            public void run() {

                
                try {
                    sem.acquire(1);
                    System.out.println("This is Thread 3, get the permit");
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    sem.release();
                }
                
                System.out.println("This is Thread 3");
                
            
            }
            
        }).start();
        
        new Thread(new Runnable(){

            @Override
            public void run() {

                
                try {
                    sem.acquire(1);
                    System.out.println("This is Thread 4, get the permit");
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    sem.release();
                }
                
                System.out.println("This is Thread 4");
                
            }
            
        }).start();
        
        new Thread(new Runnable(){

            @Override
            public void run() {
                try {
                    sem.acquire(1);
                    System.out.println("This is Thread 5, get the permit");
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    sem.release();
                }
                
                System.out.println("This is Thread 5");
            
            }
            
        }).start();
        
        new Thread(new Runnable(){

            @Override
            public void run() {

                try {
                    sem.acquire(1);
                    System.out.println("This is Thread 6, get the permit");
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    sem.release();
                }
                System.out.println("This is Thread 6");
            }   
        }).start();
    }

}

(4) Exchanger: 用來實現(xiàn)線程之間在同步點交換數(shù)據(jù)修然,用于基因算法以及管道的設計。

A synchronization point at which threads can pair and swap elements
within pairs. Each thread presents some object on entry to the
{@link #exchange exchange} method, matches with a partner thread,
and receives its partner's object on return. An Exchanger may be
viewed as a bidirectional form of a {@link SynchronousQueue}.
Exchangers may be useful in applications such as genetic algorithms
and pipeline designs.

核心算法:

   for (;;) {
   if (slot is empty) {                       // offer
        place item in a Node;
       if (can CAS slot from empty to node) {
          wait for release;
         return matching item in node;
       }
     }
     else if (can CAS slot from node to empty) { // release
       get the item in node;
     set matching item in node;
       release waiting thread;
      }
      // else retry on CAS failure
    }

Example :

class FillAndEmpty {
    Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>();
    DataBuffer initialEmptyBuffer = ... a made-up type
   DataBuffer initialFullBuffer = ...
 
    class FillingLoop implements Runnable {
      public void run() {
        DataBuffer currentBuffer = initialEmptyBuffer;
        try {
          while (currentBuffer != null) {
            addToBuffer(currentBuffer);
            if (currentBuffer.isFull())
              currentBuffer = exchanger.exchange(currentBuffer);
         }
       } catch (InterruptedException ex) { ... handle ... }
      }
    }
 
    class EmptyingLoop implements Runnable {
      public void run() {
      DataBuffer currentBuffer = initialFullBuffer;
        try {
          while (currentBuffer != null) {
            takeFromBuffer(currentBuffer);
          if (currentBuffer.isEmpty())
             currentBuffer = exchanger.exchange(currentBuffer);
       }
        } catch (InterruptedException ex) { ... handle ...}
      }
    }

    void start() {
    new Thread(new FillingLoop()).start();
    new Thread(new EmptyingLoop()).start();
    }
 }}

Exception one(會一直waiting,找找原因):


import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExchangerUsage {

    
    private static Exchanger<String> data = new Exchanger<String>();
    
    
    public static void main(String[] args) {
        
        ExchangerServer server = new ExchangerServer();
        ExchangerClient client = new ExchangerClient();
        
        server.run();
        client.run();
    }
    
    
    
    private static class ExchangerServer implements Runnable{

        @Override
        public void run() {
            String A = "A";
                    try {
                        try {
                            System.out.println("Data from client" + data.exchange(A,5,TimeUnit.SECONDS));
                        } catch (TimeoutException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                
            }
            
        }
        
        
        
        
    }
    
    
    
    private static class ExchangerClient implements Runnable{

        @Override
        public void run() {

            String B = "B";
                    try {
                        try {
                            System.out.println("Data from client" + data.exchange(B,5,TimeUnit.SECONDS));
                        } catch (TimeoutException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                
            }
            
        
        }
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末质况,一起剝皮案震驚了整個濱河市愕宋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌结榄,老刑警劉巖中贝,帶你破解...
    沈念sama閱讀 210,914評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異臼朗,居然都是意外死亡雄妥,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,935評論 2 383
  • 文/潘曉璐 我一進店門依溯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來老厌,“玉大人,你說我怎么就攤上這事黎炉≈Τ樱” “怎么了?”我有些...
    開封第一講書人閱讀 156,531評論 0 345
  • 文/不壞的土叔 我叫張陵慷嗜,是天一觀的道長淀弹。 經(jīng)常有香客問我,道長庆械,這世上最難降的妖魔是什么薇溃? 我笑而不...
    開封第一講書人閱讀 56,309評論 1 282
  • 正文 為了忘掉前任,我火速辦了婚禮缭乘,結(jié)果婚禮上沐序,老公的妹妹穿的比我還像新娘。我一直安慰自己堕绩,他們只是感情好策幼,可當我...
    茶點故事閱讀 65,381評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著奴紧,像睡著了一般特姐。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上黍氮,一...
    開封第一講書人閱讀 49,730評論 1 289
  • 那天唐含,我揣著相機與錄音浅浮,去河邊找鬼。 笑死捷枯,一個胖子當著我的面吹牛脑题,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播铜靶,決...
    沈念sama閱讀 38,882評論 3 404
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼他炊!你這毒婦竟也來了争剿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,643評論 0 266
  • 序言:老撾萬榮一對情侶失蹤痊末,失蹤者是張志新(化名)和其女友劉穎蚕苇,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凿叠,經(jīng)...
    沈念sama閱讀 44,095評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡涩笤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,448評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了盒件。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蹬碧。...
    茶點故事閱讀 38,566評論 1 339
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖炒刁,靈堂內(nèi)的尸體忽然破棺而出恩沽,到底是詐尸還是另有隱情,我是刑警寧澤翔始,帶...
    沈念sama閱讀 34,253評論 4 328
  • 正文 年R本政府宣布罗心,位于F島的核電站,受9級特大地震影響城瞎,放射性物質(zhì)發(fā)生泄漏渤闷。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,829評論 3 312
  • 文/蒙蒙 一脖镀、第九天 我趴在偏房一處隱蔽的房頂上張望飒箭。 院中可真熱鬧,春花似錦蜒灰、人聲如沸补憾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,715評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽盈匾。三九已至,卻和暖如春毕骡,著一層夾襖步出監(jiān)牢的瞬間削饵,已是汗流浹背岩瘦。 一陣腳步聲響...
    開封第一講書人閱讀 31,945評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留窿撬,地道東北人启昧。 一個月前我還...
    沈念sama閱讀 46,248評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像劈伴,于是被迫代替她去往敵國和親密末。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,440評論 2 348

推薦閱讀更多精彩內(nèi)容