Java多线程中顺序打印

本文介绍了在Java多线程编程中,使用synchronized+volatile、Lock+Condition以及Semaphore三种方法实现按顺序循环打印特定字符的过程,展示了不同同步机制的适用场景和优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

个人主页: 进朱者赤

阿里非典型程序员一枚 ,记录平平无奇程序员在大厂的打怪升级之路。 一起学习Java、大数据、数据结构算法(公众号同名

题目

在多个线程中循环打印特定字符并保持顺序的三种方法

在Java多线程编程中,有时候我们需要多个线程按照特定的顺序执行某些任务,比如循环打印特定的字符。这通常要求线程间进行协调,以确保任务按照预期的顺序执行。下面我们将介绍三种实现这一功能的方法。
在多个线程中循环打印特定字符并保持顺序的三种方法
在这里插入图片描述

在Java多线程编程中,有时候我们需要多个线程按照特定的顺序执行某些任务,比如循环打印特定的字符。这通常要求线程间进行协调,以确保任务按照预期的顺序执行。下面我们将介绍三种实现这一功能的方法。

方法一:synchronized(配合volatile关键字)

volatile关键字可以确保多线程环境中变量的可见性,但它并不保证原子性。因此,在使用volatile时,我们需要结合其他同步机制来实现顺序控制。

public class VolatilePrinting {
     
    private volatile int currentThreadIndex = 0;  
    private final int numThreads = 3;  
    private final char[] chars = {
   'A', 'B', 'C'};  
  
    public static void main(String[] args) {
     
        VolatilePrinting volatilePrinting = new VolatilePrinting();  
        Thread[] threads = new Thread[volatilePrinting.numThreads];  
        for (int i = 0; i < volatilePrinting.numThreads; i++) {
     
            final int threadIndex = i;  
            threads[i] = new Thread(() -> {
     
                while (true) {
     
                    synchronized (volatilePrinting) {
     
                        while (volatilePrinting.currentThreadIndex % volatilePrinting.numThreads != threadIndex) {
     
                            try {
     
                                volatilePrinting.wait();  
                            } catch (InterruptedException e) {
     
                                Thread.currentThread().
### 多线程打印的实现方法 多线程打印可以通过多种方式来实现,以下是常见的两种主要方法及其具体实现。 #### 方法一:基于 `synchronized` 的同步机制 通过使用 Java 中的对象锁 (`synchronized`) 和等待通知机制 (`wait()` 和 `notify()`) 来控制线程之间的协作。这种方法的核心在于确保每个线程在特定时刻只允许一个线程访问共享资源并打印字符[^2]。 ```java public class PrintABC { private static final Object lock = new Object(); private static int state = 0; public static void main(String[] args) { Thread threadA = new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (lock) { while (state % 3 != 0) { try { lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } System.out.print("A"); state++; lock.notifyAll(); } } }); Thread threadB = new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (lock) { while (state % 3 != 1) { try { lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } System.out.print("B"); state++; lock.notifyAll(); } } }); Thread threadC = new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (lock) { while (state % 3 != 2) { try { lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } System.out.print("C"); state++; lock.notifyAll(); } } }); threadA.start(); threadB.start(); threadC.start(); } } ``` 上述代码中,三个线程分别负责打印 A、B 和 C 字符。通过状态变量 `state` 控制打印顺序,并利用对象锁和等待/通知机制协调线程间的执行[^2]。 --- #### 方法二:基于 `LockSupport.park()` 和 `unpark()` 另一种实现方式是借助 `LockSupport` 类中的 `park()` 和 `unpark()` 方法。这种方式相比传统的 `wait()` 和 `notify()` 更加灵活,适合复杂的线程调度需求[^4]。 ```java import java.util.concurrent.locks.LockSupport; public class LockSupportPrintABC { private static volatile Thread t1, t2, t3; public static void main(String[] args) throws InterruptedException { t1 = Thread.currentThread(); Runnable task = () -> { for (int i = 0; i < 10; i++) { System.out.print(Thread.currentThread().getName()); LockSupport.unpark(t2); LockSupport.park(); } }; t2 = new Thread(task, "B"); t3 = new Thread(task, "C"); t2.setDaemon(true); t3.setDaemon(true); t2.start(); t3.start(); for (int i = 0; i < 10; i++) { System.out.print("A"); LockSupport.unpark(t2); LockSupport.park(); } t2.join(); t3.join(); } } ``` 在此示例中,主线程作为第一个线程启动,依次唤醒下一个线程并通过 `park()` 阻塞当前线程,从而形成严格的交替打印逻辑[^4]。 --- ### 性能对比与注意事项 - **性能方面**:`LockSupport` 提供更低级别的线程操作接口,通常比传统 `synchronized` 方式更加高效。 - **复杂度方面**:`synchronized` 结合 `wait()` 和 `notify()` 是一种经典且易于理解的方式;而 `LockSupport` 则更适合需要精细控制的场景[^3]。 无论采用哪种方法,都需要特别注意线程安全问题以及可能引发的死锁情况。 --- 问题
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进朱者赤

多多支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值