三个线程-依次打印出1-100;

package com.gxnyt.util;

/**
 * 启用三个线程-依次打印出1-100;
 * 思路:使用wait,notify+信号量(即声明的一个被同步锁-锁住的对象)
 * 有一个小坑: 在最后一个100打印时,不要再让线程进入wait()状态;
 * 因为没有别的线程可以再唤醒它;会一直处在wait()状态;而程序挂起;
 * Created by Zjt_WuLing on 2019/9/22.
 */
public class MultiThreadDemo {
    static Object lockObj = new Object();
    static volatile int printInt = 1;

    //声明一个对象,做为被锁的对象;
    // 由同步锁来对该对象上锁;
    // 在某一线程占有该对象时,判断是否可以打印(满足条件),不能打印则释放该对象(wait方法),同时通知需要该对象的其它线程(notifyAll-唤醒其它线程->进入就绪状态)
    public static void main(String[] args) {
        Thread threadFirst = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lockObj) {
                    while (printInt <= 100) {
                        if (printInt % 3 == 1) {
                            System.out.println("threadName" + Thread.currentThread().getName() + ";i===" + printInt++);
                        }
                        lockObj.notifyAll();
                        if (printInt == 101) {//这里是个小坑;最后一次不执行wait()方法
                            return;
                        }
                        try {
                            lockObj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        Thread threadSecond = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lockObj) {
                    while (printInt <= 100) {
                        if (printInt % 3 == 2) {
                            System.out.println("threadName" + Thread.currentThread().getName() + ";i===" + printInt++);
                        }
                        lockObj.notifyAll();
                        try {
                            lockObj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        Thread threadThird = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lockObj) {
                    while (printInt <= 100) {
                        if (printInt % 3 == 0) {
                            System.out.println("threadName" + Thread.currentThread().getName() + ";i===" + printInt++);
                        }
                        lockObj.notifyAll();
                        try {
                            lockObj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        threadFirst.start();
        threadSecond.start();
        threadThird.start();
    }
}

关于线程的五种状态如上图;

### 实现三个线程按顺序交替打印 #### Java 实现 在 Java 中,可以通过 `synchronized` 关键字和等待通知机制 (`wait()` 和 `notify()`) 来实现线程间的同步。以下是具体代码示例: ```java class PrintTask { private int current = 0; public synchronized void print(char c, int target) throws InterruptedException { while (current != target) { wait(); } System.out.print(c); current = (current + 1) % 3; notifyAll(); } } public class ThreadSyncExample { public static void main(String[] args) { final PrintTask task = new PrintTask(); Thread t1 = new Thread(() -> { try { for (int i = 0; i < 10; ++i) { task.print('A', 0); } } catch (InterruptedException e) {} }); Thread t2 = new Thread(() -> { try { for (int i = 0; i < 10; ++i) { task.print('B', 1); } } catch (InterruptedException e) {} }); Thread t3 = new Thread(() -> { try { for (int i = 0; i < 10; ++i) { task.print('C', 2); } } catch (InterruptedException e) {} }); t1.start(); t2.start(); t3.start(); } } ``` 上述代码中,通过共享变量 `current` 控制当前应该打印哪个字符,并使用 `wait()` 和 `notifyAll()` 方法协调线程之间的执行顺序[^4]。 --- #### C++ 实现 在 C++ 中,可以借助标准库中的 `<mutex>` 和 `<condition_variable>` 来实现类似的线程同步功能。以下是具体的代码示例: ```cpp #include <iostream> #include <thread> #include <mutex> #include <condition_variable> std::mutex mtx; std::condition_variable cv; int turn = 0; void printChar(const char ch, const int id) { for (int i = 0; i < 10; ++i) { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [&]() { return turn == id; }); std::cout << ch; turn = (turn + 1) % 3; cv.notify_all(); } } int main() { std::thread t1(printChar, 'A', 0); std::thread t2(printChar, 'B', 1); std::thread t3(printChar, 'C', 2); t1.join(); t2.join(); t3.join(); return 0; } ``` 此代码片段展示了如何利用条件变量控制线程的运行顺序,从而达到交替打印的效果[^1]。 --- #### Python 实现 Python 的多线程支持主要依赖于 `threading` 模块。下面展示了一个基于锁和事件的解决方案: ```python import threading lock = threading.Lock() cv = threading.Condition(lock) turn = 0 def print_char(ch, idx): global turn for _ in range(10): with cv: cv.wait_for(lambda: turn == idx) print(ch, end='', flush=True) turn = (turn + 1) % 3 cv.notify_all() t1 = threading.Thread(target=print_char, args=('A', 0)) t2 = threading.Thread(target=print_char, args=('B', 1)) t3 = threading.Thread(target=print_char, args=('C', 2)) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() ``` 这段代码同样采用了条件变量来管理线程间的状态转换,确保每次只有一个线程被允许访问临界区并完成其任务[^2]。 --- ### 总结 以上三种语言都实现了三线程按照指定顺序依次打印字母 A、B 和 C 各十遍的任务。每种语言都有各自的特性用于解决此类问题,在实际开发过程中可以根据项目需求和个人偏好选择合适的工具和技术栈。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值