简介
当两个进程在执行任务的时候,A调用了B,A需要等待B完成以后的通知,我们可以使用curator的屏障功能来实现。
官方文档:http://curator.apache.org/curator-recipes/barrier.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
主线程等待屏障被移除了以后继续执行
原文地址:https://www.cnblogs.com/lay2017/p/10264421.html
时间: 2024-10-12 07:53:44