两个线程线程交替打印的几种方式

本文探讨了使用多线程实现两种交替打印模式:一是交替打印大小写字母从'Aa'到'Zz',二是交替打印数字和字母从'1A'到'26Z'。通过实例展示了如何在并发环境中控制线程协作完成特定序列的输出。
部署运行你感兴趣的模型镜像

1.两个线程交替打印大小写字母“AaBbCc.....Zz”

public class RunTest {
    public static void main(String[] args) {
        Myprint mp = new Myprint();
        new Capital(mp).start();
        new Lowercase(mp).start();
}
}
 
class Myprint {
    boolean flag = true;
    int i = 0;
    int j = 0;
 
    public void Da() {
 
        while (i < 26) {
            if (flag) {
                System.out.print((char) ('A' + i));
                i++;
                this.flag = false;
            }
        }
    }
 
    public void Xiao() {
 
        while (j < 26) {
            if (!flag) {
                System.out.print((char) ('a' + j));
                j++;
                this.flag = true;
            }
        }
 
    }
}
 
class Capital extends Thread {
    Myprint my = null;
 
    public Capital(Myprint my) {
        this.my = my;
    }
 
    @Override
    public void run() {
        my.Da();//打印大写
    }
}
 
class Lowercase extends Thread {
    Myprint my = null;
 
    public Lowercase(Myprint my) {
        this.my = my;
    }
 
    @Override
    public void run() {
        my.Xiao();//打印小写
    }
}

2.两个线程交替打印数字和字母“1A2B3C......26Z”

public class PrintLetter {
    private static Object lock = new Object();

    private static Thread th1 = new Thread() {
        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 1; i <= 26; i++) {
                    System.out.println(i);
                    lock.notify();
                    try {
                        Thread.sleep(1000);
                        lock.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    private static Thread th2 = new Thread() {
        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 1; i <= 26; i++) {
                    System.out.println((char) (i + 64));
                    lock.notify();
                    try {
                        Thread.sleep(1000);
                        lock.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    public static void main(String[] args) {
        th1.start();
        th2.start();
    }
}

 3.两个线程交替打印26个小写字母“abcd......z”


public class Print_letter implements Runnable{
    char ch = 97;

    @Override
    public void run() {
        while (true){
            synchronized (this){
                notify();
                try {
                    Thread.currentThread().sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }

                if (ch < 123){
                    System.out.println(Thread.currentThread().getName() + " " + ch);
                    ch++;
                    try {
                        wait();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Print_letter t = new Print_letter();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        t2.start();
    }
}

 

您可能感兴趣的与本文相关的镜像

Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

### Java 中实现两个线程交替打印的方法 以下是几种常见的方法用于实现两个线程之间的交替打印功能: #### 方法一:使用 `synchronized` `wait/notify` 这种方法利用对象锁机制,通过调用 `wait()` 让当前线程等待,并释放锁;当其他线程完成工作后,调用 `notify()` 唤醒等待中的线程。 ```java public class AlternatePrinting { private static int count = 0; private final Object lock = new Object(); public static void main(String[] args) { AlternatePrinting ap = new AlternatePrinting(); Thread t1 = new Thread(ap::printEven, "Thread-A"); Thread t2 = new Thread(ap::printOdd, "Thread-B"); t1.start(); t2.start(); } private void printEven() { synchronized (lock) { while (count <= 10) { if (count % 2 != 0) { try { lock.wait(); // 当前线程进入等待状态 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } else { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notify(); // 唤醒另一个线程 } } } } private void printOdd() { synchronized (lock) { while (count <= 10) { if (count % 2 == 0) { try { lock.wait(); // 当前线程进入等待状态 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } else { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notify(); // 唤醒另一个线程 } } } } } ``` 此代码展示了如何通过 `wait()` `notify()` 来控制线程间的交互[^2]。 --- #### 方法二:使用 `ReentrantLock` 条件变量 相比传统的 `synchronized` 锁定方式,`ReentrantLock` 提供更灵活的锁定操作以及显式的条件支持。 ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class AlternatePrintWithLock { private Lock lock = new ReentrantLock(); private Condition conditionA = lock.newCondition(); private Condition conditionB = lock.newCondition(); private volatile boolean flag = true; // 控制哪个线程运行 public static void main(String[] args) { AlternatePrintWithLock app = new AlternatePrintWithLock(); Thread threadA = new Thread(app::taskA, "Thread-A"); Thread threadB = new Thread(app::taskB, "Thread-B"); threadA.start(); threadB.start(); } private void taskA() { lock.lock(); try { for (int i = 0; i < 5; i++) { while (!flag) { conditionA.await(); // 如果不是 A 的回合,则等待 } System.out.println(Thread.currentThread().getName() + ": " + i * 2); // 打印偶数 flag = false; conditionB.signal(); // 唤醒 B 线程 } } catch (Exception ex) { ex.printStackTrace(); } finally { lock.unlock(); } } private void taskB() { lock.lock(); try { for (int i = 0; i < 5; i++) { while (flag) { conditionB.await(); // 如果不是 B 的回合,则等待 } System.out.println(Thread.currentThread().getName() + ": " + (i * 2 + 1)); // 打印奇数 flag = true; conditionA.signal(); // 唤醒 A 线程 } } catch (Exception ex) { ex.printStackTrace(); } finally { lock.unlock(); } } } ``` 该示例说明了如何借助 `ReentrantLock` 及其关联的条件变量来协调多个线程的行为[^4]。 --- #### 方法三:使用信号量 (`Semaphore`) 信号量是一种计数器形式的同步工具,可用于管理资源访问权限或协调线程活动。 ```java import java.util.concurrent.Semaphore; public class AlternateUsingSemaphore { private Semaphore semaphoreA = new Semaphore(1); // 初始许可给 A private Semaphore semaphoreB = new Semaphore(0); public static void main(String[] args) throws InterruptedException { AlternateUsingSemaphore aus = new AlternateUsingSemaphore(); Thread threadA = new Thread(aus::taskA, "Thread-A"); Thread threadB = new Thread(aus::taskB, "Thread-B"); threadA.start(); threadB.start(); } private void taskA() { for (int i = 0; i < 5; i++) { try { semaphoreA.acquire(); // 获取许可 System.out.println(Thread.currentThread().getName() + ": " + i * 2); // 打印偶数 semaphoreB.release(); // 给 B 发放许可 } catch (InterruptedException e) { e.printStackTrace(); } } } private void taskB() { for (int i = 0; i < 5; i++) { try { semaphoreB.acquire(); // 获取许可 System.out.println(Thread.currentThread().getName() + ": " + (i * 2 + 1)); // 打印奇数 semaphoreA.release(); // 给 A 发放许可 } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 上述代码片段解释了如何运用 `Semaphore` 进行线程间通信协作。 --- #### 总结 以上三种方法各有优劣,在实际开发过程中可以根据具体需求选择合适的技术手段。如果追求简单易懂,可以选择基于 `synchronized` 的方案;对于复杂场景或者需要更高灵活性时,推荐采用 `ReentrantLock` 或者 `Semaphore`。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值