六、curator recipes之屏障barrier

简介 

当两个进程在执行任务的时候,A调用了B,A需要等待B完成以后的通知,我们可以使用curator的屏障功能来实现。

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

JavaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/barriers/DistributedBarrier.html

代码示例

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

public class Barrier {
    private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 3));
    private static String path = "/barrier/001";
    public static void main(String[] args) throws Exception {
        client.start();
        DistributedBarrier barrier = new DistributedBarrier(client, path);
        barrier.setBarrier();
        System.out.println("set barrier");
        notifyTo();
        System.out.println("wait barrier");
        barrier.waitOnBarrier();
        System.out.println("wait end");
        client.close();
    }

    public static void notifyTo() {
        new Thread(() -> {
            DistributedBarrier barrier = new DistributedBarrier(client, path);
            try {
                System.out.println("notify sleep...");
                Thread.sleep(3000);
                barrier.removeBarrier();
                System.out.println("notify remove barrier");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

输出结果

set barrier
wait barrier
notify sleep...
notify remove barrier
wait end

主线程等待屏障被移除了以后继续执行

猜你喜欢

转载自www.cnblogs.com/lay2017/p/10264421.html