线程:消费者与生产者案例

消费者与生产者必须一对一,消费者消费完了通知生产者,生产者生产完了通知消费者。
可以先定义一个共同的属性static String str;再用volatile来修饰volatile static String str;
volatile 修饰的属性为线程可见性属性
通过有参构造方法传入同一个目标
实现Runnable接口或者继承Thread类后重写run方法→用到synchronized方法:
属性类↓
public class Shuxing {
volatile static String str;
}
生产者↓
public class Producer implements Runnable{
Shuxing shuxing;
//通过有参构造传入对象
public Producer(Shuxing shuxing) {
super();
this.shuxing = shuxing;
}
public void run() {
//设置死循环
while (true) {
//synchronized锁定的对象是自定义的shuxing
synchronized (shuxing) {
//判断当shuxing的str里面有值那么该程序进入等待状态,由消费者先消费
if (shuxing.str!=null) {
try {
shuxing.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
                                //生产者生产东西给str
        shuxing.str=System.currentTimeMillis()+"";
        System.out.println("生产者已生产"+shuxing.str);
        //生产完了,唤醒消费者
        shuxing.notify();
}
}
}
}
}
消费者↓
public class Customer implements Runnable{
Shuxing shuxing;
//通过有参构造传入对象
public Customer(Shuxing shuxing) {
super();
this.shuxing = shuxing;
}
public void run() {
while (true) {
//synchronized锁定的对象是自定义的shuxing
synchronized (shuxing) {
//判断当shuxing的str里面没值那么该程序进入等待状态,由生产者先生产
if (shuxing.str==null) {
try {
shuxing.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
                                    //消费者开始消费,清空str的值
            shuxing.str=null;
            System.out.println("消费者已消费"+shuxing.str);
            //消费者已消费完毕,唤醒生产者
            shuxing.notify();
}
}
}
}
}
测试类↓
public class Text1 {
public static void main(String[] args) {
//实例化对象
Shuxing sx=new Shuxing();
//通过构造方法传入同一个对象
Thread t1=new Thread(new Producer(sx));
Thread t2=new Thread(new Customer(sx));

//开启线程
t1.start();
t2.start();
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值