码迷,mamicode.com
首页 > 其他好文 > 详细

六、curator recipes之屏障barrier

时间:2019-01-13 23:31:27      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:htm   static   color   move   start   thread   调用   nts   rgs   

简介 

当两个进程在执行任务的时候,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

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

 

六、curator recipes之屏障barrier

标签:htm   static   color   move   start   thread   调用   nts   rgs   

原文地址:https://www.cnblogs.com/lay2017/p/10264421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!