复制代码代码如下:
导入java.util.concurrent.countdownlatch;
导入java.util.concurrent.executorservice;
导入java.util.concurrent.executors;
导入java.util.concurrent.timeunit;
导入com.netflix.curator.retrypolicy;
导入com.netflix.curator.framework.curatorframework;
导入com.netflix.curator.framework.curatorframeworkfactory;
导入com.netflix.curator.framework.recipes.locks.interprocessmutex;
导入com.netflix.Curator.Retry.ExponentialBackoffry;
公共类testcuratorlock {
/**
* @param args
* @throws InterruptedException
*/
公共静态void main(string [] args)抛出InterruptedException {
// TODO自动生成的方法存根
CountDownLatch闩锁= new CountDownLatch(5);
字符串ZookeEperConnectionsTring =“ localhost:2181,localhost:2182,localhost:2183”;
retrypolicy retrypolicy =新的指数式返回(1000,3);
curatorFramework客户端= CuratorFrameWorkFactory.newclient(
ZookeEperConnectionsTring,重新质合);
client.start();
system.out.println(“客户端启动。。。。”);
executorService exec = executors.newcachedThreadPool();
for(int i = 0; i <5; i ++){
exec.submit(new Mylock(“客户端” + i,client,Latch));
}
exec.shutdown();
latch.await();
system.out.println(“所有任务执行完毕”);
client.close();
system.out.println(“客户端关闭。。。。”);
}
静态类mylock实现可运行{
私有字符串名称;
私人策展人框架客户端;
私有Countdownlatch闩锁;
public mylock(字符串名称,curatorframework客户端,Countdownlatch Latch){
this.name = name;
this.client =客户端;
this.latch =闩锁;
}
公共字符串getName(){
返回名称;
}
public void setName(字符串名称){
this.name = name;
}
@Override
public void run(){
// TODO自动生成的方法存根
InvertoCessmutex lock = new Invercessmutex(客户端,
“/test_group”);
尝试 {
if(lock.acquire(120,timeunit.seconds)){
尝试 {
//在此处的关键部分内部做一些工作
system.out.println(“ -----------” + this.name
+“获得资源-----------”);
system.out.println(“ -----------” + this.name
+“正在处理资源-----------”);
螺纹sleep(10 * 1000);
system.out.println(“ -----------” + this.name
+“资源使用完毕-----------”);
latch.countdown();
} 最后 {
lock.Release();
system.out.println(“ -----------” + this.name
+“释放-----------”);
}
}
} catch(异常E){
// TODO自动生成的捕获块
e.printstacktrace();
}
}
}
}