RCountDownLatch 分布式计数器锁的使用示例
RCountDownLatch 是 Redisson 提供的一种分布式计数器锁,类似于 Java 的 CountDownLatch。
它允许一个或多个线程等待其他操作完成后再执行,适用于分布式环境中需要协调多任务的场景。
以下示例设计来自ChatGPT。
1.示例场景
假设有 5 个任务,主线程需要等这 5 个任务全部完成后再继续执行。
public static void main(String[] args) {
// Create a Config instance and configure Redis connection
Config config = new Config();
config.useSingleServer().setAddress("redis://" + REDIS_HOST + ":" + REDIS_PORT).setPassword(redisPassword);
// Create a RedissonClient instance
RedissonClient redissonClient = Redisson.create(config);
// Create a RCountDownLatch instance
RCountDownLatch latch = redissonClient.getCountDownLatch("myCountDownLatch");
// Set the initial count of the latch
latch.trySetCount(5);
// Start the worker thread and wait for the count to reset to zero
new Thread(new Worker(redissonClient)).start();
new Thread(new Worker(redissonClient)).start();
new Thread(new Worker(redissonClient)).start();
new Thread(new Worker(redissonClient)).start();
new Thread(new Worker(redissonClient)).start();
try {
// The main thread is waiting for other threads to complete
latch.await();
System.out.println("All tasks have been completed, and the main thread continues to execute");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
redissonClient.shutdown();
}
System.out.println("end this demo!");
}
// Worker class that implements Runnable interface
static class Worker implements Runnable {
private final RedissonClient redissonClient;
public Worker(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
@Override
public void run() {
RCountDownLatch latch = redissonClient.getCountDownLatch("myCountDownLatch");
try {
System.out.println("Task " + Thread.currentThread().getName() + " start");
Thread.sleep((int) (Math.random() * 3000)); // Simulate task execution
System.out.println("Task " + Thread.currentThread().getName() + " completed");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // After each task is completed, the count is reduced by one
}
}
}
> Task :CountDownLatchExample.main()
Task Thread-1 start
Task Thread-2 start
Task Thread-3 start
Task Thread-5 start
Task Thread-4 start
Task Thread-4 completed
Task Thread-3 completed
Task Thread-1 completed
Task Thread-5 completed
Task Thread-2 completed
All tasks have been completed, and the main thread continues to execute
end this demo!
2. 使用 RCountDownLatch 在分布式系统中进行任务同步
在分布式系统中,多个 JVM 上的线程也可以通过共享的 RCountDownLatch 对象来同步任务。
只要使用相同的 Redis 服务器和相同的锁名称,就可以在多个应用实例中同步使用 RCountDownLatch。

浙公网安备 33010602011771号