redis redisson 倒计数器器示例
作用:等待足够线程执行后,执行后续操作
********************
相关接口
RCountDownLatch
public interface RCountDownLatch extends RObject, RCountDownLatchAsync {
boolean trySetCount(long var1); //设置等待线程的数量
void await() throws InterruptedException; //等待
boolean await(long var1, TimeUnit var3) throws InterruptedException; //最多等待var时间后,继续运行
void countDown(); //计数器减一
long getCount(); //获得计数器的个数
}
********************
示例
public class MyTest7 {
public static void main(String[] args){
Config config=new Config();
config.useSingleServer().setAddress("redis://***:6379").setPassword("123456");
RedissonClient client= Redisson.create(config);
RCountDownLatch countDownLatch=client.getCountDownLatch("cuntDownLatch");
countDownLatch.trySetCount(5);
ExecutorService executorService= Executors.newFixedThreadPool(5);
for (int i=0;i<5;i++){
int finalI = i;
executorService.submit(()->{
try{
System.out.println("瓜田李下 "+ finalI +"开始执行:"+System.currentTimeMillis());
Thread.sleep(1000);
System.out.println("瓜田李下 "+ finalI + "执行结束:"+System.currentTimeMillis());
}catch (Exception e){
e.printStackTrace();
}finally {
countDownLatch.countDown();
}
});
}
try{
System.out.println("主线程开始等待:"+System.currentTimeMillis());
countDownLatch.await();
System.out.println("主线程等待结束:"+System.currentTimeMillis());
}catch (Exception e){
e.printStackTrace();
}
System.out.println("主线程运行结束");
}
}
************
控制台输出
瓜田李下 0开始执行:1574648441622
瓜田李下 3开始执行:1574648441622
瓜田李下 4开始执行:1574648441622
主线程开始等待:1574648441622
瓜田李下 2开始执行:1574648441622
瓜田李下 1开始执行:1574648441622
瓜田李下 3执行结束:1574648442625
瓜田李下 4执行结束:1574648442625
瓜田李下 1执行结束:1574648442625
瓜田李下 0执行结束:1574648442625
瓜田李下 2执行结束:1574648442625
主线程等待结束:1574648442637
主线程运行结束
版权声明:本文为weixin_43931625原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。