package mpc.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @ClassName: MyLockTest
 * @Description: zookeeper锁,抄别人滴..加了一些自己的理解
 * @author mpc
 * @date 2016年10月31日 下午3:53:27
 * 
 */
public class MyLockTest {

	public static void main(String[] args) throws Exception {
		/* 定义一个数量为5的线程计数器,每个线程在执行完成后都会让他的值减一,减光光以后,主程序就不在等待,继续执行了 */
		CountDownLatch latch = new CountDownLatch(5);
		/* zookeeper集群地址列表 */
		String zkHosts = "mpc5:2181,mpc6:2181,mpc7:2181";
		/* 重试策略 这里重试3次,失败后睡眠1秒 */
		ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000,
				3);
		/* 建立一个client来和zookeeper通信 */
		CuratorFramework client = CuratorFrameworkFactory.newClient(zkHosts,
				retryPolicy);
		/* 启动client */
		client.start();

		/* 建立一个缓存线程池 */
		ExecutorService exec = Executors.newCachedThreadPool();

		for (int i = 0; i < 5; i++) {// 提交5个线程
			exec.submit(new InnerClazz(client, latch, i));
		}

		exec.shutdown();// 关闭提交器
		latch.await();// 线程计数器等待值变为0
		client.close();// client关闭
		System.err.println("所有任务都执行完成了!");

	}

	public static class InnerClazz implements Runnable {
		CuratorFramework client;
		CountDownLatch latch;
		int i;

		public InnerClazz(CuratorFramework client, CountDownLatch latch, int i) {
			this.client = client;
			this.latch = latch;
			this.i = i;
		}

		public void run() {

			InterProcessMutex lock = new InterProcessMutex(client, "/locktest");// 获得zookeeper锁
			;
			try {
				if (lock.acquire(120, TimeUnit.SECONDS)) {// 尝试获得zookeeper锁,等待时间为120秒
					try {

						System.out.println(this.i + "获得了资源并开始执行相关操作");

						TimeUnit.SECONDS.sleep(10);

						System.out.println(this.i + "使用资源完毕");
						latch.countDown();// 计数器减1
					} finally {
						lock.release();// 释放锁
						System.out.println("----------" + this.i
								+ "释放----------");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}
}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐