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
。