Java CountDownLatch和CyclicBarrier的用法

CountDownLatch 允许一个或多个线程等待其他线程完成操作。

public class CountDownLatchTest {
    public static void main(String[] args) {
        // 等待子线程的数量
        int num = 10000;
        CountDownLatch countDownLatch = new CountDownLatch(num);
        for (int i = 0; i < num; i++) {
            // CountDownLatch作为子线程对象的成员变量
            Thread t = new Thread(new Job(i, countDownLatch));
            t.start();
        }
        try{
            countDownLatch.await();
        }catch(InterruptedException e){}

        System.out.println("done");
    }
}

class Job implements Runnable {
    private int id;
    private CountDownLatch countDownLatch;

    public Job(int id, CountDownLatch countDownLatch) {
        this.id = id;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println(id);
        // 子线程执行完任务通知主线程
        countDownLatch.countDown();
    }
}

CyclicBarrier 让一组线程到达一个同步点时被阻塞,直到所有线程到达同步点,此时线程才可以继续执行同步点后面的操作。

public class CyclicBarrierTest {
    public static void main(String[] args) {
        int num = 10;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(num);
        for(int i = 0; i < num; i++){
            Thread t = new Thread(new Worker(i, cyclicBarrier));
            t.start();
        }
    }
}

class Worker implements Runnable{
    private int id;
    private CyclicBarrier cyclicBarrier;

    public Worker(int id, CyclicBarrier cyclicBarrier) {
        this.id = id;
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try{
            System.out.println("before " + id);
            cyclicBarrier.await();
        }catch(Exception e){}
        System.out.println("after " + id);
    }
}

你可能感兴趣的:(Java CountDownLatch和CyclicBarrier的用法)