下面對上面說的三個輔助類進行一個總結:dom
1)CountDownLatch和CyclicBarrier都可以實現線程之間的等待,只不過它們側重點不一樣:ide
CountDownLatch通常用於某個線程A等待若干個其餘線程執行完任務以後,它才執行;ui
而CyclicBarrier通常用於一組線程互相等待至某個狀態,而後這一組線程再同時執行;this
另外,CountDownLatch是不可以重用的,而CyclicBarrier是能夠重用的。spa
2)Semaphore其實和鎖有點相似,它通常用於控制對某組資源的訪問權限或者限流等等。線程
下面是幾個小例子code
public class CountDownLatchDemo { public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(2); System.out.println("等爸爸媽媽都來了就吃飯"); new Thread(new Runnable() { @Override public void run() { try { System.out.println("爸爸過來了"); Thread.sleep(3000); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); new Thread(new Runnable() { @Override public void run() { try { System.out.println("媽媽過來了"); Thread.sleep(3000); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); try { latch.await(); System.out.println("開飯了"); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class CyclicbarrierDemo { public static void main(String[] args) { int no = 3; final CyclicBarrier cyclicBarrier = new CyclicBarrier(no, new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"發令員:3---2---1,跑!"); } }); for (int i = 0; i < no; i++) { new Thread(new Sportsman(cyclicBarrier)).start(); } } static class Sportsman implements Runnable{ CyclicBarrier cyclicBarrier; public Sportsman(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { Thread.sleep((int)(Math.random()*1000)); System.out.println(Thread.currentThread().getName()+"準備好了,等待發令槍"); cyclicBarrier.await(); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"突突突"); } } }
public class SemaphoreDemo { public static void main(String[] args) { final Semaphore semaphore = new Semaphore(3); new Thread(new Runnable() { @Override public void run() { try { semaphore.acquire(3); System.out.println(Thread.currentThread().getName()+"獲取3個許可證"); Thread.sleep(2000L); }catch (Exception e){ e.printStackTrace(); }finally { semaphore.release(3); } } }).start(); new Thread(new Runnable() { @Override public void run() { boolean flag = false; try { flag = semaphore.tryAcquire(1, 1, TimeUnit.SECONDS); if(flag){ System.out.println(Thread.currentThread().getName()+"獲取一個許可證"); }else { System.out.println(Thread.currentThread().getName()+"獲取失敗!不能進入"); } }catch (Exception e){ e.printStackTrace(); }finally { if(flag){ //能夠釋放其餘線程的信號量,若是沒有獲取到,不要釋放,否則會有問題 semaphore.release(); } } } }).start(); } }