在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執行完畢后再執行。
這些方法都可以按照指定的順序打印多個線程,具體使用哪種方法取決于實際情況和需求。