共計 1770 個字符,預計需要花費 5 分鐘才能閱讀完成。
在 Java 中,可以使用多種方法按順序打印多個線程。
- 使用 join() 方法:在每個線程的末尾調用前一個線程的 join() 方法,確保前一個線程執行完畢后再執行下一個線程。例如:
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:CountDownLatch 是一個計數器,可以在一個或多個線程等待一組操作完成后再執行。例如:
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 和 Condition:使用 Lock 和 Condition 可以實現類似于 CountDownLatch 的功能。例如:
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 執行完畢后再執行。
這些方法都可以按照指定的順序打印多個線程,具體使用哪種方法取決于實際情況和需求。
丸趣 TV 網 – 提供最優質的資源集合!
正文完