複製代碼代碼如下:
導入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();
}
}
}
}