Version dependent:
<dependency>
<groupId>org.apache.curator</groupId>
<artifactid>curator-recipes </artifactId>
<version>2.10.0</version>
</dependency>
The sample code is as follows:
Package com.zk.lock;
Import Java.util.Random;
Import Java.util.concurrent.TimeUnit;
Import Org.apache.curator.framework.CuratorFramework;
Import Org.apache.curator.framework.recipes.locks.InterProcessMutex;
/** * Global Lock Simple Example */public class MyLock implements Runnable {private final String clientName;
Private final Interprocessmutex lock;
Public MyLock (Curatorframework client, String Lockpath, String clientName) {this.clientname = ClientName;
lock = new Interprocessmutex (client, Lockpath);
} public void work () throws Exception {//Get Global lock lock.acquire ();
try {System.out.println (ClientName + "acquired to lock");
for (int i=1;i<=3;i++) {System.out.println (clientName + "---");
TimeUnit.MILLISECONDS.sleep (Randomtime ());
} System.out.println (ClientName + "release lock");
}finally {//Release lock Lock.release ();
}} private int randomtime () {Random r = new Random ();
return R.nextint (+) + r.nextint (500); } public void Run () {try {
Work ();
} catch (Exception e) {e.printstacktrace ();
}
}
}
Package com.zk.lock;
Import Java.util.concurrent.TimeUnit;
Import Org.apache.curator.framework.CuratorFramework;
Import org.apache.curator.framework.CuratorFrameworkFactory;
Import Org.apache.curator.retry.ExponentialBackoffRetry;
/**
* Analog machine one (process i)
*/Public
class LockExample1
{
private static final String PATH = "/lock";
public static void Main (string[] args) throws Exception
{
Curatorframework client = Curatorframeworkfactory.newclient ("192.168.1.246:2181", New Exponentialbackoffretry (3));
Client.start ();
TimeUnit.SECONDS.sleep (3);
String instance = "Machine One";
for (int i=1;i<=3;i++)
{
new Thread (New MyLock (client, PATH, instance + i)). Start ();
TimeUnit.SECONDS.sleep (+);
Client.close ();
}
}
Package com.zk.lock;
Import Java.util.concurrent.TimeUnit;
Import Org.apache.curator.framework.CuratorFramework;
Import org.apache.curator.framework.CuratorFrameworkFactory;
Import Org.apache.curator.retry.ExponentialBackoffRetry;
/**
* Analog Machine II (process two)
*/Public
class LockExample2
{
private static final String PATH = "/lock";
public static void Main (string[] args) throws Exception
{
Curatorframework client = Curatorframeworkfactory.newclient ("192.168.1.246:2181", New Exponentialbackoffretry (3));
Client.start ();
TimeUnit.SECONDS.sleep (3);
String instance = "Machine Two";
for (int i=1;i<=3;i++)
{
new Thread (New MyLock (client, PATH, instance + i)). Start ();
TimeUnit.SECONDS.sleep (+);
Client.close ();
}
}
Finally, run the above two example to see the effect