有n个赛车,让它们都在起跑线上就绪后,同时出发,用Java多线程的技术把这种情况写出来

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Application {

    private static final int THREAD_COUNT = 30;
   //CountDownLatch 也可以,比较投机取巧的方法,不是最优解,最优解请参考 http://wksora.github.io/06-2014/car-competion.html
private static final CyclicBarrier ready = new CyclicBarrier(THREAD_COUNT); public static void main(String[] args) { ThreadPoolExecutor pool = new ThreadPoolExecutor(THREAD_COUNT, THREAD_COUNT, 60, TimeUnit.SECONDS, new SynchronousQueue<>()); for (int i = 0; i < THREAD_COUNT; i++) { pool.execute(new Car(i, ready)); } } } import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class Car implements Runnable { private int index; private final CyclicBarrier ready; public Car(int index, CyclicBarrier ready) { this.index = index; this.ready = ready; } @Override public void run() { try { System.out.println("Car Index " + this.index + " ready"); ready.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } finally { System.out.println("Car Index " + this.index + " run"); } } }

 

posted @ 2020-05-22 14:43  bookc  阅读(373)  评论(0编辑  收藏  举报