1.创建连接对象
String connectString = "localhost:2181,localhost:2182,localhost:2183"; //connectString
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(connectString) //connectString
.sessionTimeoutMs(5000) //sessionTimeout
.retryPolicy(new RetryOneTime(3000)) //retryPolicy->retry one times after 3000ms
.build();
client.start(); //开始连接
2. 分布式普通锁
//第一个参数指明client,第二个参数指明锁的路径
InterProcessLock lock = new InterProcessMutex(client, "/wanna");
lock.acquire();
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(3);
System.out.println(i);
}
lock.release();
启动两个进程,我们发现只有当进程1执行完,才能轮到进程2执行。当进程1被强制关闭(宕机),过了一定时间之后进程2也能执行,因此我们可以发现这个锁很智能,不会产生死锁,宕机会自动释放掉锁。
3. 分布式读写锁
//第一个参数指定client,第二个参数指定路径path
InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/wanna");
final InterProcessMutex readLock = lock.readLock(); //获取读锁对象
final InterProcessMutex writeLock = lock.writeLock(); //获取写锁对象
//模拟写进程
new Thread(() -> {
System.out.println("Write thread is running");
try {
writeLock.acquire(); //加上写锁
for (int i = 0; i < 10; i++) {
System.out.println("write-" + i);
TimeUnit.SECONDS.sleep(2);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//释放写锁
writeLock.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
//模拟读进程
new Thread(() -> {
System.out.println("Read thread is running");
try {
//加上读锁
readLock.acquire();
for (int i = 0; i < 10; i++) {
System.out.println("read-" + i);
TimeUnit.SECONDS.sleep(2);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//释放读锁
readLock.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
如果先获得了读锁,那么就得先把读进程执行完才能执行写进程,如果先获得了写锁,那么就得先把写进程执行完才能执行读进程,和单机版的JUC下的读写锁类似。
网友评论