java -12生产者和消费者

生产者和消费者问题的描述图
在这里插入图片描述
通过上图,我们可以发现:

生产者和消费者使用的都是同一个资源(肉包子)

所以,当使用线程的时候,这两类的锁也是同一把锁(为了避免出现线程安全问题)

例子:学生信息的录入和获取

* 资源类:Student
  * 设置学生数据:SetThread(生产者)
  * 获取学生数据:GetThread(消费者)
  * 测试类:StudentDemo

  • 资源类
	public class Student {
		String name;
		int age;
	}
  • 生产者
public class SetThread implements Runnable {
    private int x = 0;

    // 因为SetThread和Getthread两个类使用的都是同一个资源
    // 所以,在创建一个资源对象,再通过构造方法传递给其它的类
    private Student s;

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

    public void run() {
        // 录入信息(生产者)
        while (true) {

            // 加锁,且SetThread和Getthread两个类使用的是同一把锁,所以锁的对象是资源对象s
            synchronized (s) {
                if (x % 2 == 0) {
                    s.name = "张三";
                    s.age = 23;
                } else {
                    s.name = "李四";
                    s.age = 24;
                }
                x++;
            }
        }
    }

}
  • 消费者
public class GetThread implements Runnable {

    private Student s;
    public GetThread(Student s){
        this.s = s;
    }
    public void run() {
            //获取信息  消费者
            //锁的对象,同SetThread
        while(true){
            synchronized (s){
                System.out.println(s.name +"--" + s.age);
            }
        }

    }

}
  • 测试类
public class StudentDemo {
    public static void main(String[] args) {
        
        //创建资源对象
        Student s = new Student();
        
        //创建录入和获取类的对象
        SetThread st = new SetThread(s);
        GetThread gt = new GetThread(s);
        
        //创建线程对象
        Thread t1 = new Thread(st);
        Thread t2 = new Thread(gt);
        
        //启动线程
        t1.start();
        t2.start();

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值