java併發包concurrent之Atomic,CountDownLatch,CyclicBarrier,Semaphore
常用的併發包 Atomic
常用的併發類CountDownLatch,CyclicBarrier,Semaphore
Atomic:分析下面程式碼
常規的demo public class Test002 { public static void main(String[] args) { automicThread[] ac = new automicThread[10]; for (int i = 0; i < ac.length; i++) { ac[i] = new automicThread(); ac[i].start(); } } } class automicThread extends Thread { private static int count = 0; @Override public void run() { for (int i = 0; i < 1000; i++) { count++; } System.out.println(getName() + "-------" + count); } }
輸出結果為:
Thread-0-------2633 Thread-7-------4633 Thread-3-------2633 Thread-1-------3633 Thread-2-------3633 Thread-5-------5633 Thread-9-------6633 Thread-8-------8008 Thread-4-------9071 Thread-6-------8071 此過程中出現了執行緒安全問題,說明沒有同步 static volitate關鍵字均沒保證資料的安全性 只是保證資料及時共享
Automic併發包下面的對八大基本型別的併發原子類實現保證資料的原子性。
public class Test002 { public static void main(String[] args) { automicThread[] ac = new automicThread[10]; for (int i = 0; i < ac.length; i++) { ac[i] = new automicThread(); ac[i].start(); } } } class automicThread extends Thread { private static AtomicInteger count = new AtomicInteger(); @Override public void run() { for (int i = 0; i < 1000; i++) { count.incrementAndGet(); 相當於++操作 java本身的++操作是不安全的 } System.out.println(getName() + "-------" + count); } }
輸出結果如下
Thread-1-------1000 Thread-0-------2000 Thread-7-------3000 Thread-2-------4000 Thread-6-------5120 Thread-5-------6000 Thread-9-------7000 Thread-8-------8834 Thread-3-------9000 Thread-4-------10000
AtomicInteger保證資料的原子性,具體實現這裡不作說明。
CountDownLatch:(記數器)是一個同步工具類,它允許一個或多個執行緒一直等待,直到其他執行緒的操作執行完後再執行
如何將執行緒按照自己想要的順序執行:CountDownLatch設定基數量 當 countDownLatch.countDown()滿足大於0 則用不會執行 countDownLatch.await()後面的程式碼。保證執行緒與執行緒之間的同步執行操作 如下 正常情況 System.out.println("主執行緒執行完畢");必會先執行輸出
public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(2);//初始化2個計數器 new Thread() { @Override public void run() { countDownLatch.countDown();//計數器減1 System.out.println("我是子執行緒"); } }.start(); new Thread() { @Override public void run() { countDownLatch.countDown();//計數器減1 System.out.println("我是子執行緒"); } }.start(); countDownLatch.await();//當 countDownLatch.countDown();減少到0時候才執行以下程式碼 System.out.println("主執行緒執行完畢"); } }
CyclicBarrier:(記數器)與CountDownLatch類似
Semaphore:訊號量Semaphore semaphore = new Semaphore(5);表示搶資源,當前執行緒如果大於5個 那麼第六個執行緒必須等待前面的執行緒釋放才能得到時間片段
以上←一個簡單的說明 在實際應用中用的並不是太多 ,做個筆記簡單記錄下,以便後面遇到可以查閱