复制代码代码如下::
Import Java.util.Concurrent.Countdownlatch;
import Java.util.concurrent.executorService;
import Java.util.concurrent.executors;
Import Java.util.Concurrent.TimeUnit;
import com.netflix.curator.retrypolicy;
com.netflix.curator.framework.curatorframework;
com.netflix.curator.framework.curatorframeworkFactory;
com.netflix.curator.framework.recipes.locks.interprocessmutex;
import com.netflix.curator.retry.exponentialbackoffretry;
public class testcuratorlock {
/**
* @param args
* @Throws InterruptedException
*/
public static void main (String [] args) löst InterruptedException {
// Todo automatisch generierte Methode Stub
Countdownlatch Latch = new Countdownlatch (5);
String zookeeperconnectionString = "Localhost: 2181, Localhost: 2182, Localhost: 2183";
Retypolicy Retypolicy = New Exponentialbackoffretry (1000, 3);
CuratorFramework Client = CuratorFrameworkFactory.newclient (
zookeeperconnectionString, retypolicy);
Client.Start ();
System.out.println ("客户端启动。。。。");
ExecutorService Exec = Executors.NewCachedThreadpool ();
für (int i = 0; i <5; i ++) {
exec.Submit (neuer mylock ("client" + i, client, latch));
}
exec.shutdown ();
latch.aait ();
System.out.println ("所有任务执行完毕");
client.close ();
System.out.println ("客户端关闭。。。。");
}
Statische Klasse mylock implementiert runnable {
privater Zeichenfolge Name;
privater Kuratorframework -Kunden;
privater Countdownlatch -Verriegelung;
public mylock (String -Name, CuratorFramework -Client, Countdownlatch -Latch) {
this.name = name;
this.client = client;
this.latch = latch;
}
public String getName () {
Rückgabename;
}
public void setName (String Name) {
this.name = name;
}
@Override
public void run () {
// Todo automatisch generierte Methode Stub
Interprocessmutex lock = new interprocessmutex (Client,
"/test_group");
versuchen {
if (lock.acquire (120, TimeUnit.Seconds)) {
versuchen {
// Hier arbeiten einige Arbeiten im kritischen Abschnitt hier
System.out.println ("----------" + this.name
+ "获得资源 ----------");
System.out.println ("----------" + this.name
+ "正在处理资源 ----------");
Thread.sleep (10 * 1000);
System.out.println ("----------" + this.name
+ "资源使用完毕 ----------");
latch.countdown ();
} Endlich {
lock.Release ();
System.out.println ("----------" + this.name
+ "释放 ----------");
}
}
} catch (Ausnahme e) {
// todo automatisch generierter Fangblock
E. printstacktrace ();
}
}
}
}