多线程交替输出奇数偶数1到1000(wait/notify)

本文介绍了一个Java程序,使用wait/notify机制在两个线程中交替打印1到1000的奇数和偶数,确保了线程安全并实现了同步控制。

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

先上代码:

public class Printer {

    private static final Object lock = new Object();

    private static int flg = 1;

    private static void start() {
        //打印奇数
        Thread t1 = new Thread(() -> {
            int printer = 1;
            while (printer <= 1000) {
                synchronized (lock) {
                    if (flg == 1) {
                        System.out.println(printer);
                        flg = 2;
                        printer += 2;
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });

        //打印偶数
        Thread t2 = new Thread(() -> {
            int printer = 2;
            while (printer <= 1000) {
                synchronized (lock) {
                    if (flg == 2) {
                        System.out.println(printer);
                        flg = 1;
                        printer += 2;
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        t1.start();
        t2.start();
    }

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

思路与多线程交替输出abc100次(wait/notify)-优快云博客 类似,可先参考,解析稍后补充!

### C++多线程交替打印奇偶数的实现 在C++中,可以利用`std::mutex`和`std::condition_variable`来控制多个线程之间的同步操作。通过这种方式,可以让两个线程分别负责打印奇数偶数,并确保它们按照顺序交替执行。 以下是基于引用中的思路[^1]以及标准库功能的一个具体实现: #### 使用条件变量和互斥锁 为了实现交替打印,可以通过设置一个共享计数器并配合条件变量完成线程间的协调工作。下面是一个完整的代码示例: ```cpp #include <iostream> #include <thread> #include <mutex> #include <condition_variable> using namespace std; class OddEvenPrinter { public: OddEvenPrinter() : current(1) {} void printOdd() { unique_lock<mutex> lock(m); while (current <= N) { cv.wait(lock, [&]() { return current % 2 != 0 || current > N; }); if (current <= N && current % 2 != 0) { cout << "Odd thread prints: " << current << endl; ++current; } cv.notify_all(); } } void printEven() { unique_lock<mutex> lock(m); while (current <= N) { cv.wait(lock, [&]() { return current % 2 == 0 || current > N; }); if (current <= N && current % 2 == 0) { cout << "Even thread prints: " << current << endl; ++current; } cv.notify_all(); } } private: int current; static constexpr int N = 100; // 打印范围上限 mutex m; condition_variable cv; }; int main() { OddEvenPrinter printer; thread t1(&OddEvenPrinter::printOdd, ref(printer)); thread t2(&OddEvenPrinter::printEven, ref(printer)); t1.join(); t2.join(); return 0; } ``` 这段代码定义了一个名为`OddEvenPrinter`的类,其中包含了用于管理状态的成员变量(如当前数值`current`),并通过互斥量`m`保护这些资源。同时使用了条件变量`cv`来进行线程间的通知机制[^3]。 当调用`main()`函数时,创建了两个独立运行的工作线程`t1`和`t2`,分别对应于打印奇数偶数的任务。这两个线程会依据设定好的规则依次访问临界区内的数据结构,在满足特定条件下才允许继续执行其任务。 此设计模式遵循生产者消费者模型的思想,即每次只允许其中一个线程进入临界区域处理业务逻辑,而另一个则处于等待状态直到被通知轮到它为止[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值