创建闭锁,确保能连接到zk服务器。
// 创建闭锁
final CountDownLatch countDownLatch = new CountDownLatch(1);
String connectString="139.196.31.237:2181";
int sessionTimeout=5000;
// 创建ZooKeeper对象
ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("连接zk成功!watchedEvent:"+watchedEvent.getState());
countDownLatch.countDown();
}
});
// 利用闭锁的await()方法产生阻塞,等待连接zk的线程执行完毕
countDownLatch.await();
详情请参考:https://www.2cto.com/net/201803/725311.html