十二、curator recipes之双重屏障DoubleBarrier

简介

curator实现了单个屏障barrier和双重屏障DoubleBarrier,单个屏障就是在一个进程里面设置了屏障,并等待其它进程去移除这个屏障,否则一直阻塞。双重屏障就是设置了两道屏障,两个线程都到达第一个屏障的时候执行下面的内容,然后两个都到达第二个屏障的时候继续执行下面的内容。

官方文档:http://curator.apache.org/curator-recipes/double-barrier.html

javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.html

代码示例

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class DoubleBarrierDemo {
    private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 2));
    private static String path = "/barrier/0001";
    static {
        client.start();
    }

    public static void main(String[] args) throws Exception {
        DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, path, 2);
        new Thread(() -> {
            try {
                Thread.sleep(5000);
                System.out.println("thread0 entering");
                DistributedDoubleBarrier barrier1 = new DistributedDoubleBarrier(client, path, 2);
                barrier1.enter();
                System.out.println("thread0 entered and leaving");
                Thread.sleep(3000);
                barrier1.leave();
                System.out.println("thread0 leaved");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        System.out.println("main entering");
        barrier.enter();
        System.out.println("main entered and leaving");
        barrier.leave();
        System.out.println("main leaved");
        Thread.sleep(50000);
        client.close();
    }
}

  

posted @ 2019-01-16 00:49  __lay  阅读(495)  评论(0编辑  收藏  举报