
CountDownLatch是一个同步工具类,它通过一个计数器来实现的,初始值为线程的数量。每当一个线程完成了自己的任务,计数器的值就相应得减1。当计数器到达0时,表示所有的线程都已执行完毕,然后在等待的线程就可以恢复执行任务。
举例:学生考试,学生和监考老师都各自是一个线程,学生答完试卷交卷就可以离开,监考老师需要在所有的考生交完试卷才能离开。
package spring.test2.service;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@Service
public class TestService {
public static void main(String[] args) {
CountDownLatch countDown = new CountDownLatch(2);
List<String> result = Collections.synchronizedList(new ArrayList<>());
new Thread(()->{
try {
Thread.sleep(2000); // 考十花费1秒
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
countDown.countDown();
result.add("试卷1");
System.out.println("学生1交卷 离开");
}).start();
new Thread(()->{
try {
Thread.sleep(1000);// 考试花费2秒
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
countDown.countDown();
result.add("试卷2");
System.out.println("学生2交卷 离开");
}).start();
try {
if(countDown.await(2, TimeUnit.HOURS)){ // 考试时间最长2小时
// 考试结束,老师离开
System.out.println(result);
System.out.println("老师离开");
}else{
System.out.println("超时");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}