线程同步辅助类

CountDownLatch


private CountDownLatch latch = new CountDownLatch(1); 
 
    /**
     * 连接zookeeper
     */ 
    public void connectZookeeper() throws Exception { 
        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() { 
            public void process(WatchedEvent event) { 
                try { 
                    // 连接建立时, 打开latch, 唤醒wait在该latch上的线程 
                    if (event.getState() == KeeperState.SyncConnected) { 
                        latch.countDown(); 
                    } 
 
                    // 发生了waitPath的删除事件 
                    if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) { 
                        doSomething(); 
                    } 
                } catch (Exception e) { 
                    e.printStackTrace(); 
                } 
            } 
        }); 
 
       // 等待连接建立 
        latch.await(); 

猜你喜欢

转载自cesymm.iteye.com/blog/2008221