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

Curator实现分布式锁

时间:2015-09-09 17:48:24      阅读:732      评论:0      收藏:0      [点我收藏+]

标签:

public static void main (String[] args) {
    String servers = "10.128.7.20:2181,10.128.7.20:2182,10.128.7.20:2183";
    CuratorFramework curator = CuratorFrameworkFactory.builder().retryPolicy(new ExponentialBackoffRetry(10000, 3)).connectString(servers).build();
    curator.start();
    final InterProcessMutex lock = new InterProcessMutex(curator, "/global_lock");

    Executor pool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i ++) {
        pool.execute(new Runnable() {
            public void run() {
                try {
                    lock.acquire();
                    System.out.println(Thread.currentThread().getName());
                    TimeUnit.SECONDS.sleep(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    try {
                        lock.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


}


Curator实现分布式锁

标签:

原文地址:http://my.oschina.net/u/2250599/blog/503807

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