溫馨提示×

java多線程怎么按順序打印

小億
141
2023-11-10 13:13:14
欄目: 編程語言

在Java中,可以使用多種方法按順序打印多個線程。

  1. 使用join()方法:在每個線程的末尾調(diào)用前一個線程的join()方法,確保前一個線程執(zhí)行完畢后再執(zhí)行下一個線程。例如:
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();
  1. 使用CountDownLatch:CountDownLatch是一個計數(shù)器,可以在一個或多個線程等待一組操作完成后再執(zhí)行。例如:
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執(zhí)行完畢后再執(zhí)行。

  1. 使用Lock和Condition:使用Lock和Condition可以實現(xiàn)類似于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執(zhí)行完畢后再執(zhí)行。

這些方法都可以按照指定的順序打印多個線程,具體使用哪種方法取決于實際情況和需求。

0