使用生产者和消费者模式实现交替输出

package com.javase.wait和notify.homework;

/*
   使用生产者和消费者模式实现交替输出:
      假设有两个线程,输出结果如下:
                    t1--->1
                    t2--->2
                    t1--->3
                    t2--->4
                    t1--->5
                    t2--->6
                    ......
 */
 /*   
    分析:
        1、两个线程交替执行
        2、t1线程始终输出奇数,t2线程始终输出偶数
        3、两个线程共享一个数字,每个线程执行都要对这个数字进行++
                class Num {
                    int i;
                }
 */

public class Homework {
    public static void main(String[] args) {
//        创建一个数字(该数字两个线程共享)
        Num num = new Num();
//        创建两个线程(共享num)
        Thread t1 = new Thread(new Odd(num));
        Thread t2 = new Thread(new Even(num));
//        改名
        t1.setName("t1");
        t2.setName("t2");
//        启动线程
        t1.start();
        t2.start();
    }
}
//数字类
class Num {
    //属性(给定一个初始值1,因为从数字1开始,为此肯定奇数线程最先执行)
    int i = 1;
}
//奇数线程
class Odd implements Runnable{
    //因为奇数线程与偶数线程同时共享数字类,为此将数字类对象作为奇数线程和偶数线程的属性
    Num num;

    //有参构造方法
    public Odd(Num num) {
        this.num = num;
    }

    //重写run()方法
    @Override
    public void run() {
        //一直输出奇数
        while (true){
            synchronized (num){
                //如果是偶数进入等待
                if (num.i % 2 == 0){
                    try {
                        num.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //程序运行到此说明是奇数开始输出
                System.out.println(Thread.currentThread().getName() + "--->" + num.i);
                //数字输出后需要加1
                num.i++;
                //程序到此延迟2秒(目的是每2秒输出1个数字,减缓程序运行速度)
                try {
                    Thread.sleep(1000 * 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //唤醒偶数线程
                num.notify();
            }
        }
    }
}
//偶数线程
class Even implements Runnable{
    //因为奇数线程与偶数线程同时共享数字类,为此将数字类对象作为奇数线程和偶数线程的属性
    Num num;

    //有参构造方法
    public Even(Num num) {
        this.num = num;
    }

    //重写run()方法
    @Override
    public void run() {
        //一直输出偶数
        while (true){
            synchronized (num){
                //是奇数进入等待
                if (num.i % 2 == 1){
                    try {
                        num.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //程序运行到此说明是偶数开始输出
                System.out.println(Thread.currentThread().getName() + "--->" + num.i);
                //输出后++
                num.i++;
                //睡眠2秒(目的是每2秒输出1个数字,减缓程序运行速度)
                try {
                    Thread.sleep(1000 * 2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //唤醒奇数线程
                num.notify();
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解决这个问题。你可以使用一个共享的队列来实现。其中一个线程作为生产者,负责往队列中添加数据,另一个线程作为消费者,负责从队列中取出数据并输出。 以下是一个简单的 Python 代码示例: ```python import threading import time queue = [] condition = threading.Condition() class ProducerThread(threading.Thread): def run(self): global queue nums = range(1, 5) global condition for num in nums: condition.acquire() queue.append(num) print("t1 --->", num) condition.notify() condition.release() time.sleep(1) class ConsumerThread(threading.Thread): def run(self): global queue global condition while True: condition.acquire() if not queue: print("t2 waiting") condition.wait() print("t2 notified") num = queue.pop(0) print("t2 --->", num) condition.release() time.sleep(1) producer = ProducerThread() consumer = ConsumerThread() producer.start() consumer.start() ``` 在这个示例中,我们定义了一个队列和一个条件变量 `condition`。生产者线程 `ProducerThread` 负责往队列中添加数据,并在添加完数据后使用 `notify()` 方法通知消费者线程 `ConsumerThread` 可以取出数据了。消费者线程则负责从队列中取出数据并输出使用 `acquire()` 和 `release()` 方法来加锁和解锁,保证线程安全。当队列为空时,消费者线程会调用 `wait()` 方法等待通知。 运行这个程序,你会得到以下输出: ``` t1 ---> 1 t2 waiting t1 ---> 2 t2 notified t2 ---> 1 t1 ---> 3 t2 waiting t1 ---> 4 t2 notified t2 ---> 2 t2 ---> 3 t2 ---> 4 ``` 可以看到,两个线程交替输出了所需的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值