小测试用例:实现线程的顺序执行方案:(1)使用countdownlatch方法(2)使用thread和join方法实现第一个方案包com.high.current08;importjava.util.concurrent.CountDownLatch;publicclassOrderThread1扩展线程{私有CountDownLatch闩锁;publicOrderThread1(CountDownLatchlatch){this.latch=latch;}@Overridepublicvoidrun(){System.out.println("线程:"+Thread.currentThread().getName()+"正在运行");尝试{Thread.sleep(5000);}catch(InterruptedExceptione){e.printStackTrace();}System.out.println("线程:"+Thread.currentThread().getName()+"结束");latch.countDown();}}packagecom.high.current08;importjava.util.concurrent.CountDownLatch;publicclassTestOrder1{publicstaticvoidmain(String[]args)throwsInterruptedException{intnumber=3;CountDownLatchlatch=newCountDownLatch(数字);长t1=System.currentTimeMillis();for(inti=0;i<3;i++){OrderThread1demo=newOrderThread1(latch);演示.start();}latch.await();System.out.println("main结束,耗时"+(System.currentTimeMillis()-t1)+"ms");}}第二种方法packagecom.high.current08;publicclassOrderThread2extendsThread{@Overridepublicvoidrun(){System.out.println("Thread:"+Thread.currentThread().getName()+"is跑步”);尝试{Thread.sleep(5000);}catch(InterruptedExceptione){e.printStackTrace();}System.out.println("线程:"+Thread.currentThread().getName()+"结束");}}packagecom.high.current08;publicclassTestOrder2{publicstaticvoidmain(String[]args)throwsInterruptedException{OrderThread2thread1=newOrderThread2();OrderThread2thread2=newOrderThread2();OrderThread2thread3=newOrderThread2();长t1=System.currentTimeMillis();thread1.start();thread2.start();thread3.start();thread1.join();thread2.join();thread3.join();System.out.println("main结束,耗时"+(System.currentTimeMillis()-t1)+"ms");}}GITHUB
