在Java中,可以使用多种方法按顺序打印多个线程。
Thread t1 = new Thread(() -> { System.out.println("线程1"); }); Thread t2 = new Thread(() -> { try { t1.join(); System.out.println("线程2"); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread t3 = new Thread(() -> { try { t2.join(); System.out.println("线程3"); } catch (InterruptedException e) { e.printStackTrace(); } }); t1.start(); t2.start(); t3.start(); CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch2 = new CountDownLatch(1); Thread t1 = new Thread(() -> { try { latch1.await(); System.out.println("线程1"); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch2.countDown(); } }); Thread t2 = new Thread(() -> { try { latch2.await(); System.out.println("线程2"); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread t3 = new Thread(() -> { try { latch2.await(); System.out.println("线程3"); } catch (InterruptedException e) { e.printStackTrace(); } }); t1.start(); t2.start(); t3.start(); latch1.countDown(); 这样线程t2和t3会等待线程t1执行完毕后再执行。
Lock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Thread t1 = new Thread(() -> { try { lock.lock(); System.out.println("线程1"); condition2.signal(); } finally { lock.unlock(); } }); Thread t2 = new Thread(() -> { try { lock.lock(); condition2.await(); System.out.println("线程2"); condition1.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }); Thread t3 = new Thread(() -> { try { lock.lock(); condition1.await(); System.out.println("线程3"); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }); t1.start(); t2.start(); t3.start(); 这样线程t2和t3会等待线程t1执行完毕后再执行。
这些方法都可以按照指定的顺序打印多个线程,具体使用哪种方法取决于实际情况和需求。