复制代码代码如下:
impor java.util.concurrent.countdownlatch;
impor java.util.concurrent.executorservice;
impor java.util.concurrent.Executors;
impor java.util.concurrent.timeunit;
impor com.netflix.curator.retrypolicy;
impor com.netflix.curator.framework.curatorframework;
impor com.netflix.curator.framework.curatorframeworkFactory;
impor com.netflix.curator.framework.recipes.locks.interprocessMutex;
impor com.netflix.curator.retry.Exponentialbackoffretry;
TestCuratorLock kelas publik {
/**
* @param args
* @Throws InterruptedException
*/
public static void main (string [] args) melempar interruptedException {
// TODO Stub Metode yang dihasilkan otomatis
Latch Countdownlatch = Countdownlatch baru (5);
String ZooKeeperconnectionString = "LocalHost: 2181, LocalHost: 2182, LocalHost: 2183";
Retrypolicy retrypolicy = ExponentialBackRetry baru (1000, 3);
CuratorFramework Client = CuratorFrameworkFactory.NewClient (
ZooKeeperconnectionstring, retrypolicy);
client.start ();
System.out.println ("客户端启动。。。。");
ExecutorService exec = executors.newcachedThreadpool ();
untuk (int i = 0; i <5; i ++) {
exec.submit (mylock baru ("klien" + i, klien, kait));
}
exec.shutdown ();
latch.Await ();
System.out.println ("所有任务执行完毕");
client.close ();
System.out.println ("客户端关闭。。。。");
}
kelas statis mylock mengimplementasikan runnable {
nama string pribadi;
Klien PRIVATE CuratorFramework;
latch hitung mundur pribadi;
mylock publik (nama string, klien kuratorframework, latch countdownlatch) {
this.name = name;
this.client = klien;
this.latch = latch;
}
Public String getName () {
nama pengembalian;
}
public void setName (nama string) {
this.name = name;
}
@Mengesampingkan
public void run () {
// TODO Stub Metode yang dihasilkan otomatis
InterprocessMutex lock = InterprocessMutex baru (klien,
"/test_group");
mencoba {
if (lock.acquire (120, timeunit.seconds)) {
mencoba {
// Lakukan beberapa pekerjaan di dalam bagian kritis di sini
System.out.println ("----------" + this.name
+ "获得资源 ----------");
System.out.println ("----------" + this.name
+ "正在处理资源 ----------");
Thread.sleep (10 * 1000);
System.out.println ("----------" + this.name
+ "资源使用完毕 ----------");
latch.countdown ();
} Akhirnya {
lock.release ();
System.out.println ("----------" + this.name
+ "释放 ----------");
}
}
} catch (Exception e) {
// TODO Blok tangkapan yang dihasilkan otomatis
e.printstacktrace ();
}
}
}
}