复制代码代码如下:
import java.util.concurrent.countdownLatch;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.timeunit;
import com.netflix.curator.rcrypolicy;
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.ExPonentialBackOffryry;
Public Class TestCuratorLock {
/**
* @param args
* @throws interrumpedException
*/
public static void main (string [] args) lanza interruptedException {
// TODO STUB de método generado automático
CountdownLatch Latch = new CountdownLatch (5);
String ZookeePerconnectionString = "Localhost: 2181, localhost: 2182, localhost: 2183";
Retrypolicy retrypolicy = new ExponentialBackOffryrry (1000, 3);
CuratorFramework Client = CuratorFrameWorkFactory.NewClient (
ZookeePerConnectionString, RitryPolicy);
client.start ();
System.out.println ("客户端启动。。。。");
EjecutorService exec = Ejecutors.NewCachedThreadPool ();
para (int i = 0; i <5; i ++) {
exec.submit (new MyLock ("Cliente" + I, Cliente, Latch));
}
exec.shutdown ();
Latch.Await ();
System.out.println ("所有任务执行完毕");
client.close ();
System.out.println ("客户端关闭。。。。");
}
clase estática MyLock implementos runnables {
nombre de cadena privada;
Curatorframework de curador privado;
pestillo privado CountdownLatch;
public mylock (nombre de cadena, CuratorFramework Client, CountdownLatch Latch) {
this.name = name;
this.client = cliente;
this.latch = Latch;
}
public String getName () {
nombre de retorno;
}
public void setName (nombre de cadena) {
this.name = name;
}
@Anular
public void run () {
// TODO STUB de método generado automático
InterprocessMutex Lock = New InterProcessMutex (Cliente,
"/test_group");
intentar {
if (Lock.Acquire (120, TimeUnit.seconds)) {
intentar {
// Haz algo de trabajo dentro de la sección crítica aquí
System.out.println ("----------" + this.name
+ "获得资源 ----------");
System.out.println ("----------" + this.name
+ "正在处理资源 ----------");
Thread.sleep (10 * 1000);
System.out.println ("----------" + this.name
+ "资源使用完毕 ----------");
Latch.CountDown ();
} finalmente {
Lock.Release ();
System.out.println ("----------" + this.name
+ "释放 ----------");
}
}
} Catch (Exception e) {
// bloque de captura generado automático
E.PrintStackTrace ();
}
}
}
}