java多线程怎么按顺序打印

38次阅读
没有评论

共计 1770 个字符,预计需要花费 5 分钟才能阅读完成。

在 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 执行完毕后再执行。

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1770字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)