Java并发编程中的三种并发工具
1.CountDownLatch:允许一个或多个线程等待其他线程完成操作,有点类似join方法
public class CountDownLatchTest{ static CountDownLatch count = new CountDownLatch(2); //表示N个等待的点 public static void main(String[] args){ Thread thread = new Thread(new Runnable(){ @Override public void run(){ //do something System.out.println("111"); count.countDown(); System.out.println("222"); count.countDown(); } }).start(); c.await(); System.out.println("333"); } }
2.CyclicBarrier同步屏障:当一个线程到达同步屏障时被阻塞,知道所有的线程都到达时屏障才会开启。
public class CyclicBarrierTest{ static CyclicBarrier cb = new CyclicBarrier(2); public static void main(String[] args){ Thread thread = new Thread(new Runnable(){ @Override public void run(){ try{ cb.await(); }catch(Exception e){ } System.out.println("111"); } }).start(); try{ cb.await(); }catch(Exception e){ } System.out.println("222"); } }
同时CyclicBarrier也提供了当有线程先到达屏障时不用等待其他线程的处理方法。
public class CyclicBarrierTest2{ static CyclicBarrier cb = new CyclicBarrier(2,new A()); public static void main(String[] args){ Thread thread = new Thread(new Runnable(){ @Override public void run(){ try{ cb.await(); }catch(Exception e){ } System.out.println("111"); } }).start(); try{ cb.await(); }catch(Exception e){ } System.out.println("222"); } //先到达的线程,执行这个方法 static class A implements Runnable{ public void run(){ System.out.println("333"); } } }
3.Semphore信号量:用来协调控制并发的线程数。
public class SemphoreTest{ private static final int THREAD_COUNT = 30; private static Semphore sem = new Semphore(10); private ExecutorService threadPool = Executors.newFixedThreadPool(Thread_COUNT); public static void main(String[] args){ for(int i = 0;i < THREAD_COUNT;i++){ threadPool.execute(new Runnable(){ @Override public void run(){ try{ sem.acqiure(); System.out.println("gogogo"); sem.release(); }catch(Exception e){ } } }); } threadPool.shutDown(); } }