---
title: "java Curator实现分布式锁"
author: "艾伦蓝"
date: "2017-09-05T14:39:05Z"
tags: []
categories: ["编程语言"]
slug: "java-curator"
draft: true
lastmod: "2017-09-05T14:33:47Z"
id: 2392200
url: "https://forlan.iteye.com/blog/2392200"
---

\[size=medium]\[color=red]\[b]Curator实现分布式锁主要依赖于zookeeper\[/b]\[/color]\[/size] \[code="java"] // Curator实现分布式锁 CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181") .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build(); // 必须先启动 否则无效过 client.start(); final InterProcessMutex lock = new InterProcessMutex(client, "/zk-xxx/childs"); for(int i=0;i&lt;10;i++){ new Thread(){ @Override public void run() { try { lock.acquire(); System.out.println(code.getCode()); lock.release(); } catch (Exception e) { e.printStackTrace(); } } }.start(); } \[/code] \[code="java"] class GenerateCode{ public String getCode(){ SimpleDateFormat fomat = new SimpleDateFormat("HH:mm:ss|SSS"); System.out.println("你的线程号："+Thread.currentThread().getName()); return fomat.format(new Date()); } } \[/code] \[code="xml"] org.apache.curator curator-recipes 2.7.0 \[/code]