Java

java多线程怎么按顺序打印

小亿
141
2023-11-10 13:13:14
栏目: 编程语言

在Java中,可以使用多种方法按顺序打印多个线程。

  1. 使用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();
  1. 使用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执行完毕后再执行。

  1. 使用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执行完毕后再执行。

这些方法都可以按照指定的顺序打印多个线程,具体使用哪种方法取决于实际情况和需求。

0
看了该问题的人还看了