Java多线程关于生产者和消费者

生产者--消费者,二者共享数据(Student对象),这里,生产者是SetStudent, 消费者是GetStudent。生产者负责放物品到Student中,消费者使用wait( )等待生产者的通知。当得到通知后,消费者取出物品,并且用notify( )通知生产者,可以再放下一批物品。

(1)生产者仅仅在仓储未满时候生产,仓满则停止生产。
(2)消费者仅仅在仓储有产品时候才能消费,仓空则等待。
(3)当消费者发现仓储没产品可消费时候会通知生产者生产。
(4)生产者在生产出可消费产品时候,应该通知等待的消费者去消费

//学生实体类作为共享资源
class Student {
    private String name;// 姓名
    private int age;// 年龄
    boolean flag;// 标记变量,判断当前学生对象是否已创建赋值好

    //生产者的功能  ,为studnet对象赋值
    public synchronized void set(String name, int age) {

        if (this.flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name;
        this.age = age;

        this.flag = true;
        this.notify();//唤醒正在等待此对象的单个线程监控。如果有任何线程在这个对象上等待,其中一个线程被唤醒。选择是任意的
    }

    //消费者的功能,打印sutdent对象的内容
    public synchronized void get() {
        if (!this.flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(name + ":::" + age);

        this.flag = false;
        this.notify();
    }

}

// 模拟生产者线程类
class SetStudent implements Runnable {

    // 共享资源s
    private Student s;
    private int x = 0;

    public SetStudent(Student s) {
        this.s = s;
    }


    public void run() {
        while (true) {
            if (x % 2 == 0) {
                s.set("郭靖", 27);
            } else {
                s.set("黄蓉", 18);
            }
            x++;
        }
    }

}

// 模拟消费者线程类
class GetStudent implements Runnable {

    // 共享资源s
    private Student s;

    public GetStudent(Student s) {
        this.s = s;
    }

    public void run() {
        while (true) {
            s.get();
        }
    }

}

// 测试类
public class Demo3{

    public static void main(String[] args) {
        Student s = new Student();

        SetStudent ss = new SetStudent(s);
        GetStudent gs = new GetStudent(s);

        Thread t1 = new Thread(ss, "生产者");
        Thread t2 = new Thread(gs, "消费者");

        t1.start();
        t2.start();
    }

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值