构造函数接收一个int类型的参数做为计数器,若是想等待N个点,就传入N。当调用CountDownLatch的countDown方法时,N就会减一,直至减为零。使用await方法等待,当N的值变为零,执行await的线程继续执行。多线程
public class CountDownTest { static CountDownLatch c = new CountDownLatch(2); static ExecutorService pool = Executors.newFixedThreadPool(2); public static void main(String agrs[]){ pool.execute(new Runnable() { public void run() { try { TimeUnit.MILLISECONDS.sleep(3); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("This is A"); c.countDown(); } }); pool.execute(new Runnable() { public void run() { try { TimeUnit.MILLISECONDS.sleep(3); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("This is B"); c.countDown(); } }); try { c.await(); }catch (InterruptedException e){ } System.out.println("This is main"); } }
可循环使用的屏障。它要作的事情,让一组线程到达屏障时被阻塞,直到最后一个线程到达屏障时,屏障才会打开,全部被屏障拦截的线程才会继续运行。并发
默认构造方法CyclicBarrier(int parties),其参数表示屏障拦截的线程数,每一个线程调用await方法告诉CyclicBarrier已经到达屏障,而后当前线程阻塞。函数
public class CylicBarrierTest { static CyclicBarrier c = new CyclicBarrier(2); static ExecutorService pool = Executors.newFixedThreadPool(2); public static void main(String args[]){ pool.execute(new Runnable() { public void run() { System.out.println("this is A"); try { c.await(); System.out.println("this is Aa"); }catch (Exception e){ e.printStackTrace(); } } }); pool.execute(new Runnable() { public void run() { System.out.println("this is B"); try { c.await(); System.out.println("this is Bb"); }catch (Exception e){ e.printStackTrace(); } } }); pool.shutdown(); } }
CountDownLatch的计数器只使用一次,而CyclicBarrier的计数器可使用reset方法重置,重复使用ui
控制有限哥线程使用资源。使用方法 Semaphore ss = new Semaphore(N), N表示最大的并发量,每一个线程使用资源前调用ss.acquire()方法获取权限,使用完后调用ss.release()方法释放权限。this
它提供一个同步点,在这个同步点,两个线程能够交换彼此的数据。spa
public class ExchangeTest { private static final Exchanger<String> exgr = new Exchanger<String>(); private static ExecutorService pool = Executors.newFixedThreadPool(2); public static void main(String args[]){ pool.execute(new Runnable() { public void run() { String A = "银行流水A"; try { A = exgr.exchange(A); System.out.println("A 当前的值:" + A); }catch (InterruptedException e){ } } }); pool.execute(new Runnable() { public void run() { String B = "银行流水B"; try { B = exgr.exchange(B); System.out.println("B 当前的值:" + B); }catch (InterruptedException e){ } } }); pool.shutdown(); }