zoukankan      html  css  js  c++  java
  • 有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"); } } }
  • 相关阅读:
    分治策略
    uva 11424
    lightoj 1214
    lightoj 1282 && uva 11029
    lightoj 1341
    zoj 2369 Two Cylinders
    几种素数筛法
    lightoj 1245
    hdoj 1299 Diophantus of Alexandria
    求前n项正整数的倒数和
  • 原文地址:https://www.cnblogs.com/fqybzhangji/p/12163557.html
Copyright © 2011-2022 走看看