【并发编程】- CountDownLatch 设置等待超时

1,483 阅读4分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第15天,点击查看活动详情

接着上一篇文章 # 【并发编程】- 多个CountDownLatch 线程集合同步点

运行结果如下:

裁判员在等待选手的到来!
运动员使用不同方式到达起跑点,正向这边走!
运动员使用不同方式到达起跑点,正向这边走!
运动员使用不同方式到达起跑点,正向这边走!
运动员使用不同方式到达起跑点,正向这边走!
运动员使用不同方式到达起跑点,正向这边走!
运动员Thread-4 到起跑点了!  
等待裁判说准备!
运动员Thread-0 到起跑点了!  
等待裁判说准备!
运动员Thread-1 到起跑点了!  
等待裁判说准备!
运动员Thread-2 到起跑点了!  
等待裁判说准备!
运动员Thread-3 到起跑点了!  
等待裁判说准备!
裁判员看到所有运动员来了,各就各位前巡视用时5秒
各就各位!准备起跑姿势! 
各就各位!准备起跑姿势! 
各就各位!准备起跑姿势! 
各就各位!
各就各位!准备起跑姿势! 
各就各位!准备起跑姿势! 
发令枪响起!
运动员Thread-4起跑 并且跑过程用时不确定
运动员Thread-2起跑 并且跑过程用时不确定
运动员Thread-1起跑 并且跑过程用时不确定
运动员Thread-3起跑 并且跑过程用时不确定
运动员Thread-0起跑 并且跑过程用时不确定
运动员Thread-2到达终点!
运动员Thread-0到达终点!
运动员Thread-1到达终点!
运动员Thread-4到达终点!
运动员Thread-3到达终点!
所有运动员到达,统计比赛名次!
方法await(long timeout,TimeUnit unit)的使用

设置await超时时间代码如下:

public class CountDownLatchService {

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public void runMethod(){
        try {
            System.out.println("运动员"+Thread.currentThread().getName()+"准备好了!时间:"+System.currentTimeMillis());
            countDownLatch.await(5, TimeUnit.SECONDS);
            System.out.println("运动员"+Thread.currentThread().getName()+"结束!时间:"+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

创建运动员线程代码如下:

public class Runner implements Runnable {


    private CountDownLatchService service;

    public Runner(CountDownLatchService service){
        super();
        this.service=service;
    }

    @Override
    public void run() {
        service.runMethod();
    }
}

运行类代码如下:

public class RunnerMatch {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatchService service = new CountDownLatchService();
        Runner[] runners = new Runner[10];
        for (int i = 0; i < runners.length ; i++) {
            runners[i] = new Runner(service);
            Thread thread = new Thread(runners[i]);
            thread.setName(String.valueOf(i+1));
            thread.start();
        }
    }
}

运行结果如下:

运动员1准备好了!时间:1650097938258
运动员2准备好了!时间:1650097938258
运动员3准备好了!时间:1650097938258
运动员4准备好了!时间:1650097938258
运动员5准备好了!时间:1650097938258
运动员6准备好了!时间:1650097938258
运动员7准备好了!时间:1650097938258
运动员8准备好了!时间:1650097938258
运动员9准备好了!时间:1650097938258
运动员10准备好了!时间:1650097938273
运动员6结束!时间:1650097943273
运动员7结束!时间:1650097943273
运动员9结束!时间:1650097943273
运动员8结束!时间:1650097943273
运动员3结束!时间:1650097943273
运动员4结束!时间:1650097943273
运动员1结束!时间:1650097943273
运动员10结束!时间:1650097943273
运动员2结束!时间:1650097943273
运动员5结束!时间:1650097943273

​ 方法await(long timeout,TimeUnit unit)的作用使线程在指定的最大时间单位内进入WAITING状态,如果超过这个时间则自动唤醒,程序继续向下运行,参数timeout是等待时间,而unit参数是时间的单位。由结果可看出实现了5秒后继续向下运行的效果。