复制代码代码如下:
นำเข้า 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.exponentialbackfreter;
Public Class TestCuratorLock {
-
* @param args
* @throws interruptedException
-
โมฆะคงที่สาธารณะหลัก (String [] args) พ่น InterruptedException {
// todo วิธีการที่สร้างขึ้นอัตโนมัติสตับ
countdownlatch latch = new countdownlatch (5);
zookeeperconnectionString = "localhost: 2181, localhost: 2182, localhost: 2183";
retrypolicy retrypolicy = ใหม่ exponentialbackfretry (1,000, 3);
CuratorFramework Client = CuratorFrameworkFactory.NewClient (
zookeeperconnectionstring, retrypolicy);
client.start ();
System.out.println ("客户端启动。。。。");
ExecutorService exec = executors.newcachedthreadpool ();
สำหรับ (int i = 0; i <5; i ++) {
exec.submit (ใหม่ mylock ("ไคลเอนต์" + i, ไคลเอนต์, latch));
-
Exec.Shutdown ();
latch.await ();
System.out.println ("所有任务执行完毕");
client.close ();
System.out.println ("客户端关闭。。。。");
-
คลาสคงที่ MyLock ใช้งาน Runnable {
ชื่อสตริงส่วนตัว;
ไคลเอนต์ผู้ดูแลส่วนตัว
ลัทช์นับถอยหลังส่วนตัว;
Public MyLock (ชื่อสตริง, CuratorFramework Client, Countdownlatch Latch) {
this.name = ชื่อ;
this.client = ไคลเอนต์;
this.latch = latch;
-
สตริงสาธารณะ getName () {
ชื่อคืน;
-
โมฆะสาธารณะ setName (ชื่อสตริง) {
this.name = ชื่อ;
-
@Override
โมฆะสาธารณะเรียกใช้ () {
// todo วิธีการที่สร้างขึ้นอัตโนมัติสตับ
interprocessMutex lock = ใหม่ 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 (Exception e) {
// todo catch block ที่สร้างอัตโนมัติ
E.PrintStackTrace ();
-
-
-
-