countDownLatch.await(10, TimeUnit.SECONDS);使用案例
时间: 2024-02-21 10:01:51 浏览: 239
CountDownLatch.await(long timeout, TimeUnit unit) 方法可以让等待线程在指定的时间内等待其他线程完成任务,如果等待时间超过了指定时间,等待线程将会继续执行。这个方法比 CountDownLatch.await() 更加灵活,可以避免在某些情况下出现线程一直等待的情况。
以下是一个使用 CountDownLatch.await(long timeout, TimeUnit unit) 的案例:
```java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int taskCount = 3;
CountDownLatch latch = new CountDownLatch(taskCount);
Thread t1 = new Thread(new Task(latch, 5000));
Thread t2 = new Thread(new Task(latch, 10000));
Thread t3 = new Thread(new Task(latch, 15000));
t1.start();
t2.start();
t3.start();
boolean allTasksFinished = latch.await(10, TimeUnit.SECONDS);
if (allTasksFinished) {
System.out.println("All tasks have finished, now executing main task.");
} else {
System.out.println("Some tasks have not finished within the timeout period, now executing main task.");
}
}
static class Task implements Runnable {
private CountDownLatch latch;
private long sleepTime;
public Task(CountDownLatch latch, long sleepTime) {
this.latch = latch;
this.sleepTime = sleepTime;
}
@Override
public void run() {
try {
System.out.println("Task started: " + Thread.currentThread().getName());
Thread.sleep(sleepTime);
System.out.println("Task finished: " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
```
在上面的例子中,我们创建了一个 CountDownLatch 对象并设置了计数器的初始值为 3。然后创建了 3 个线程分别执行不同时间的任务。在等待其他线程完成任务时,我们使用了 CountDownLatch.await(10, TimeUnit.SECONDS) 方法,表示等待 10 秒钟,如果其他线程在这个时间内没有完成任务,等待线程将会继续执行。当所有任务都执行完毕时,主任务将会开始执行。
阅读全文