Java並發CountDownLatch編程開發樣本

來源:互聯網
上載者:User

在多線程編程時,常常需要解決線程同步問題,在上一節講得BlockQueue的take和put方法,是通過阻塞來控制生產者和消費者執行流程,它其實也是在解決線程同步問題。另外線上程同步問題還可以通過很多方式解決比如訊號量,柵欄,閉鎖。今天所說的CountDownLatch就是一種閉鎖同步類,它的作用就像一扇門,在達到結束狀態之前門是關閉的,並且沒有任何線程可以通過這扇門,當達到了結束狀態,門開啟,所有的線程可以通過。並且結束後,不會再關閉。

CountDownLatch簡介

CountDownLatch是一種閉鎖的實現,它通過一個計數器來實現。
1、在初始化時,指定等待線程的數量。
2、每個線程結束時,調用countDown將等待數量減1
3、它會有一個await方法,來等待線程全部執行結束。

CountDownLatch用法

/**
CountDownLatch類是一個同步計數器,構造時傳入int參數,該參數就是計數器的初始值,每調用一次countDown()方法,計數器減1,計數器大於0 時,await()方法會阻塞程式繼續執行
CountDownLatch如其所寫,是一個倒計數的鎖存器,當計數減至0時觸發特定的事件。利用這種特性,可以讓主線程等待子線程的結束。下面以一個類比運動員比賽的例子加以說明。
*/
  import java.util.concurrent.CountDownLatch;
  import java.util.concurrent.Executor;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
 
  public class CountDownLatchDemo {
     private static final int PLAYER_AMOUNT = 5;
     public CountDownLatchDemo() {
         // TODO Auto-generated constructor stub   
      }
     /**
      * @param args
      */
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         //對於每位運動員,CountDownLatch減1後即結束比賽
         CountDownLatch begin = new CountDownLatch(1);
         //對於整個比賽,所有運動員結束後才算結束
         CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
         Player[] plays = new Player[PLAYER_AMOUNT];
        
         for(int i=0;i<PLAYER_AMOUNT;i++)
             plays[i] = new Player(i+1,begin,end);
        
         //設定特定的線程池,大小為5
         ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
         for(Player p:plays)
             exe.execute(p);            //分配線程
         System.out.println("Race begins!");
         begin.countDown();
         try{
             end.await();            //等待end狀態變為0,即為比賽結束
         }catch (InterruptedException e) {
             // TODO: handle exception
             e.printStackTrace();
         }finally{
             System.out.println("Race ends!");
         }
         exe.shutdown();
     }
 }
 
接下來是Player類

import java.util.concurrent.CountDownLatch;
 
 
 public class Player implements Runnable {
 
     private int id;
     private CountDownLatch begin;
     private CountDownLatch end;
     public Player(int i, CountDownLatch begin, CountDownLatch end) {
         // TODO Auto-generated constructor stub
         super();
         this.id = i;
         this.begin = begin;
         this.end = end;
     }
 
     @Override
     public void run() {
         // TODO Auto-generated method stub
         try{
             begin.await();        //等待begin的狀態為0
             Thread.sleep((long)(Math.random()*100));    //隨機分配時間,即運動員完成時間
             System.out.println("Play"+id+" arrived.");
         }catch (InterruptedException e) {
             // TODO: handle exception
             e.printStackTrace();
         }finally{
             end.countDown();    //使end狀態減1,最終減至0
         }
     }
 }


代碼以及使用情境樣本

假設如下情境:在一個批次程式中,一次從一個遠程介面中,拉取資料需要耗時非常長的時間,這時考慮到使用多線程去拉,可以減少線程等待的時間。這時就可以使用CountDownLatch來做線程同步,來保證每個線程都執行完成來繼續下面的流程。

public class CountDownLatchDemo {

    private static ExecutorService executor= Executors.newFixedThreadPool(5);

    public static void main(String[] args){

        CountDownLatch countDownLatch=new CountDownLatch(10);

        for(int index=0;index<10;index++) {
            executor.execute(new Task(index*10,(index+1)*10,countDownLatch));
        }

        try {
            System.out.println("開始等待線程執行...");
            countDownLatch.await();
            System.out.println("全部線程執行完畢");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private static class Task implements Runnable{

        private int startIndex;

        private int count;

        private CountDownLatch countDownLatch;

        public Task(int startIndex, int count,CountDownLatch countDownLatch) {
            this.startIndex = startIndex;
            this.count = count;
            this.countDownLatch=countDownLatch;
        }

        @Override
        public void run() {
            try {
                Thread.sleep((long) (1000 * Math.random()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId()+"執行完成。");
            countDownLatch.countDown();
        }
    }
}

以上代碼類比了上述假設中得情境。其中使用了線程池來做線程管理,這些對象也將在後續介紹。
輸出結果如下:

開始等待線程執行...
12執行完成。
11執行完成。
12執行完成。
11執行完成。
13執行完成。
13執行完成。
9執行完成。
10執行完成。
12執行完成。
11執行完成。
全部線程執行完畢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.