concurrent-辅助类

CountDownLatch闭锁

public class XxxTest {
    /***
     * 伪代码
     */
    CountDownLatch latch = new CountDownLatch(3);//初始化一个数量为3的闭锁
    Thread t1 = new Thread();//开启三个线程
    Thread t2 = new Thread();
    Thread t3 = new Thread();
    t1: latch.countDown();//每个线程的逻辑:给闭锁数量减1
    t2: latch.countDown();
    t3: latch.countDown();
    latch.await();//同时阻塞主线程,直到每个子线程执行完毕
}

CyclicBarrier栅栏

public class CyclicBarrierTest2 {

    private static int SIZE = 5;
    private static CyclicBarrier cb;
    public static void main(String[] args) {

        cb = new CyclicBarrier(SIZE, new Runnable () {
            public void run() {
                System.out.println("CyclicBarrier's parties is: "+ cb.getParties());
            }
        });

        // 新建5个任务
        for(int i=0; i<SIZE; i++)
            new InnerThread().start();
    }

    static class InnerThread extends Thread{
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " wait for CyclicBarrier.");

                // 将cb的参与者数量加1
                cb.await();

                // cb的参与者数量等于5时,才继续往后执行
                System.out.println(Thread.currentThread().getName() + " continued.");
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Semaphore信号量


public class XxxTest {
        public static void main(String[] args) {
            Semaphore sem = new Semaphore(10);//初始化一个大小为10的信号量池子
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        sem.acquire(5);//从信号量池子中申请5个信号量,如果池子余量不够,则等待,直到能申请到后继续往下执行
                    }catch (Exception e){
                    }finally {
                        sem.release();//释放信号量到池中
                    }
                }
            });
            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        sem.acquire(7);//从信号量池子中申请7个信号量,如果池子余量不够,则等待,直到能申请到后继续往下执行
                    }catch (Exception e){
                    }finally {
                        sem.release();//释放信号量到池中
                    }
                }
            });
            t1.start();
            t2.start();
        }
}

猜你喜欢

转载自www.cnblogs.com/yanhui007/p/12587295.html