public class ZkCuratorLockUtil {
public static String idGenerator(IGenerateGlobalId iGenerateGlobalId,InterProcessMutex lock) {
String idGenerator = null;
try {
lock.acquire();
idGenerator = iGenerateGlobalId.idGenerator();
System.out.println(Thread.currentThread().getName() + ",生成ID:" + idGenerator);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
lock.release();
} catch (Exception e) {
e.printStackTrace();
}
}
return idGenerator;
}
public static void main(String[] args) {
CuratorFramework client = ZkCuratorConfig.client;
client.start();
InterProcessMutex lock = new InterProcessMutex(client, "/mutex");
for (int i = 0; i < 10; i++) {
idGenerator(new SequenceUnLockGenerateGlobalIdImpl(),lock);
}
}
}
public class ZkCuratorTask implements Runnable{
private CountDownLatch latch;
private IGenerateGlobalId iGenerateGlobalId;
private InterProcessMutex lock;
public ZkCuratorTask(CountDownLatch latch, IGenerateGlobalId iGenerateGlobalId,InterProcessMutex lock) {
this.latch = latch;
this.iGenerateGlobalId = iGenerateGlobalId;
this.lock = lock;
}
@Override
public void run() {
try {
latch.await();
ZkCuratorLockUtil.idGenerator(iGenerateGlobalId, lock);
System.out.printf("类名名称:%s 订单号:%s \r\n", iGenerateGlobalId.getClass().getName(),iGenerateGlobalId.idGenerator());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CuratorFramework client = ZkCuratorConfig.client;
client.start();
InterProcessMutex lock = new InterProcessMutex(client, "/mutex");
ExecutorService pool = Executors.newCachedThreadPool();
final CountDownLatch latch = new CountDownLatch(1);
IGenerateGlobalId globalId = new SequenceUnLockGenerateGlobalIdImpl();
for (int i = 0; i < 10; i++) {
pool.submit(new ZkCuratorTask(latch, globalId,lock));
}
latch.countDown();
pool.shutdown();
}
}