复制代码代码如下:
Importer java.util.concurrent.CountDownLatch;
Importer java.util.concurrent.executorService;
Importer java.util.concurrent.executors;
Importer java.util.concurrent.TimeUnit;
import com.netflix.curator.retrypolicy;
import com.netflix.curator.framework.curatorframework;
import com.netflix.curator.framework.curatorFrameworkFactory;
import com.netflix.curator.framework.recipes.locks.interprocessmutex;
import com.netflix.curator.retry.exponentialBackOffretry;
classe publique TestCuratorlock {
/ **
* @param args
* @Throws InterruptedException
* /
public static void main (String [] args) lance InterruptedException {
// Talage de méthode générée automatiquement de TODO
CountdownLatch Latch = Nouveau compte à rebours (5);
String ZooKeEnConnectionString = "LocalHost: 2181, localhost: 2182, localhost: 2183";
RetryPolicy RetryPolicy = Nouveau exponentielbackoffretry (1000, 3);
Curatorframework client = curatorframeworkfactory.newClient (
ZOOKEEPERConnectionString, RetryPolicy);
client.start ();
System.out.println ("客户端启动。。。。");
ExecutorService exec = exécutor.NewCachedThreadPool ();
pour (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 ("客户端关闭。。。。");
}
classe statique Mylock implémente Runnable {
nom de chaîne privé;
Cirmurator Framework Client;
Latch à compte à rebours privé;
public mylock (nom de chaîne, CuratorFramework Client, CountdownLatch Latch) {
this.name = name;
this.client = client;
this.latch = latch;
}
public String getName () {
nom de retour;
}
public void setName (nom de chaîne) {
this.name = name;
}
@Outrepasser
public void run () {
// Talage de méthode générée automatiquement de TODO
InterprocessMutex Lock = Nouveau interprocessmutex (client,
"/ test_group");
essayer {
if (lock.acquire (120, timeunit.seconds)) {
essayer {
// travaille à l'intérieur de la section critique ici
System.out.println ("----------" + this.name
+ "获得资源 ----------");
System.out.println ("----------" + this.name
+ "正在处理资源 ----------");
Thread.Sleep (10 * 1000);
System.out.println ("----------" + this.name
+ "资源使用完毕 ----------");
latch.CountDown ();
} enfin {
Lock.release ();
System.out.println ("----------" + this.name
+ "释放 ----------");
}
}
} catch (exception e) {
// Bloc de capture généré automatiquement de TODO
e.printStackTrace ();
}
}
}
}