复制代码代码如下:
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.exponentialbackoffretryをインポートします。
Public Class TestCuratorLock {
/**
* @param args
* @throws arturnedexception
*/
public static void main(string [] args)throws arturnedexception {
// TODO自動生成方法スタブ
CountDownLatch latch = new CountDownLatch(5);
string zookeeperconnectionstring = "localhost:2181、localhost:2182、localhost:2183";
retrypolicy retrypolicy = new ExponentialBackOfftretry(1000、3);
curatorframework client = curatorframeworkfactory.newclient(
ZooKeeperconnectionString、retrypolicy);
client.start();
system.out.println( "客户端启动。。。。");
executorservice exec = executors.newcachedthreadpool();
for(int i = 0; i <5; i ++){
exec.submit(new MyLock( "Client" + i、client、latch));
}
exec.shutdown();
latch.await();
system.out.println( "所有任务执行完毕");
client.close();
system.out.println( "客户端关闭。。。。");
}
静的クラスのmylockは実行可能{
プライベート文字列名;
プライベートキュレーターフレームワーククライアント。
プライベートカウントダウンラッチラッチ。
Public MyLock(String Name、KuratorFrameworkクライアント、CountDownLatch Latch){
this.name = name;
this.client = client;
this.latch = latch;
}
public string getName(){
返品名;
}
public void setName(string name){
this.name = name;
}
@オーバーライド
public void run(){
// TODO自動生成方法スタブ
interprocessmutex lock = new interprocessmutex(クライアント、
"/test_group");
試す {
if(lock.acquire(120、timeunit.seconds)){
試す {
//ここで重要なセクション内でいくつかの作業を行う
System.out.println( "----------" + this.name
+ "获得资源---------");
System.out.println( "----------" + this.name
+ "正在处理资源---------");
thread.sleep(10 * 1000);
System.out.println( "----------" + this.name
+ "资源使用完毕---------");
latch.countdown();
} ついに {
lock.release();
System.out.println( "----------" + this.name
+ "释放---------");
}
}
} catch(例外e){
// TODO自動生成キャッチブロック
e.printstacktrace();
}
}
}
}