最近有道多线程的面试题:
五个运动员(相当于五个线程),一个裁判(Main线程),满足以下三个条件,如何实现:
1.同时起跑
2.要所有运动员都到达终点以后才能进行下一个环节
3.如果有一个运动员摔跤了(异常处理),就终止这次比赛,让所有运动员都到终点进行下个环节
可以使用CountDownLatch和CyclicBarrier来解决这个问题
public class Test {
private static ExecutorService service = Executors.newCachedThreadPool();
private static CountDownLatch countDownLatch = new CountDownLatch(5);
private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
private static Integer count = 0;
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
for (int i=0;i<5;i++) {
service.execute( new Athlete(countDownLatch, cyclicBarrier, i));
}
//所有线程执行结束后
countDownLatch.await();
System.out.println("下一个环节");
}
}
class Athlete implements Runnable{
private final CountDownLatch countDownLatch;
private final CyclicBarrier cyclicBarrier;
private final int id;
Athlete(CountDownLatch countDownLatch,CyclicBarrier cyclicBarrier,int id){
this.countDownLatch = countDownLatch;
this.cyclicBarrier = cyclicBarrier;
this.id = id;
}
@Override
public void run() {
try {
//等待其他线程
cyclicBarrier.await();
System.out.println(id+"跑步中--------");
System.out.println(id+"跑完了--------");
}catch (Exception e){
System.out.println(id+"受伤啦!");
}finally {
//执行完后,进行countDown()
this.countDownLatch.countDown();
}
}
}
结果:当运动员全部正常结束时,进行下一个环节:
当运动员中有人受伤时,我们可以用idea 2018的新功能,throw Exception,来模拟运动员受伤:
搞定!,如果你还在用eclipse,那么强烈给你安利一波idea。