import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessLock; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.Random; import java.util.concurrent.CountDownLatch; /** * 文件功能:zookeeper分佈式鎖 * 故事:5個線程(模擬分佈式進程)爭奪分佈式鎖 */ public class CuratorLocksExample { private static InterProcessLock distributeLock=null; private static CountDownLatch count=new CountDownLatch(5); public static void main(String[] args) { CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.64.128:2181", new ExponentialBackoffRetry(1000, 3)); client.start(); distributeLock=new InterProcessMutex(client,"/mylock"); for(int i=0;i<5;i++){ new Thread(new MyHostThread("線程"+i,client,distributeLock,count)).start(); } try { count.await(); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("釋放客戶端,斷開zk鏈接"); client.close(); } } } class MyHostThread implements Runnable{ private String name; private CuratorFramework client; private InterProcessLock lock; private CountDownLatch count; public MyHostThread(String name,CuratorFramework client,InterProcessLock lock,CountDownLatch count){ this.name=name; this.client=client; this.lock=lock; this.count=count; } @Override public void run() { System.out.println(this.name + "開始競爭鎖"); try { lock.acquire();//阻塞等待.. System.out.println(this.name + "獲取到鎖"); Thread.sleep(new Random().nextInt(2000));//模擬業務處理2s內 } catch (Exception e) { e.printStackTrace(); }finally { try { System.out.println(this.name + "業務處理完,釋放鎖"); lock.release();//釋放鎖 count.countDown(); } catch (Exception e) { e.printStackTrace(); } } } }
預期輸出:java
線程3開始競爭鎖
線程0開始競爭鎖
線程4開始競爭鎖
線程1開始競爭鎖
線程2開始競爭鎖
線程0獲取到鎖
線程0業務處理完,釋放鎖
線程4獲取到鎖
線程4業務處理完,釋放鎖
線程1獲取到鎖
線程1業務處理完,釋放鎖
線程3獲取到鎖
線程3業務處理完,釋放鎖
線程2獲取到鎖
線程2業務處理完,釋放鎖
釋放客戶端,斷開zk鏈接apache