Java实现多个线程一起并发执行

it2023-06-14  70

面试人员:用Java的多线程模拟一个赛马,马场上有10匹马,要求他们同时起跑

设计到的Java多线程技术:CountDownLatch或者CyclicBarrier

/** * <p> * <p>Title:testCountDownLatch.java</p > * <p>Description: </p > * <p>Date:2020/10/20 14:53</p > * * @author wsh * @version 1.0 */ public class testCountDownLatch { CountDownLatch countDownLatch = new CountDownLatch(1); private void runThread(){ ExecutorService executorService = Executors.newFixedThreadPool(10); for(int i=0;i<10 ;i++){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } executorService.submit(new Runnable() { @Override public void run() { try { countDownLatch.await(); System.out.println("Thread:"+Thread.currentThread().getName()+",time: "+System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }); } countDownLatch.countDown(); } public static void main(String[] args) { testCountDownLatch test = new testCountDownLatch(); test.runThread(); } }

运行结果:

/** * <p> * <p>Title:CyclicBarrierTest.java</p > * <p>Description: 做到10个线程同时start</p > * <p>Date:2020/10/20 14:41</p > * * @author wsh * @version 1.0 */ public class CyclicBarrierTest { /** * CyclicBarrier 适用再多线程相互等待,直到到达一个屏障点。并且CyclicBarrier是可重用的。 */ CyclicBarrier cyclicBarrier = new CyclicBarrier(10); private void runThread() { ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } executorService.submit(createThread(i)); } } private Thread createThread(int i) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { cyclicBarrier.await(); System.out.println("Thread:" + Thread.currentThread().getName() + "准备完毕,time:" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }); thread.setName("name" + i); return thread; } public static void main(String[] args) { CyclicBarrierTest test = new CyclicBarrierTest(); test.runThread(); } }

运行结果:

最新回复(0)