package MiaoSha; import org.apache.curator.CuratorConnectionLossException; 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; /** * 缺点:速度有点慢 * 不会出现写三台计只有两台机存活二报错的问题 */ public class TestDistributedLock { //10个共享资源 private static int count = 100; public static void main(String[] args) { //等待时长,重试次数 ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 10); CuratorFramework client = CuratorFrameworkFactory.builder() .connectString("bigdata166:2181,bigdata167:2181,bigdata168:2181") .retryPolicy(retry) .build(); //客户端启动 client.start(); //创建锁 节点自动创建 InterProcessMutex lock = new InterProcessMutex(client, "/mylock"); //测试线程 for (int i = 0; i < 100; i++) { new Thread(new Runnable() { @Override public void run() { try { lock.acquire(); printCountNumber(); } catch (Exception e) { e.printStackTrace(); }finally { try { lock.release(); } catch (Exception e) { e.printStackTrace(); } } } }).start(); } } private static void printCountNumber() throws InterruptedException { System.out.println("==========="+Thread.currentThread().getName()+"=============="); System.out.println("当前共享资源的数量为:"+count); count--; // Thread.sleep(12); System.out.println("==========="+Thread.currentThread().getName()+"=============="); } }