不同线程间的等待唤醒机制

具体来说是线程间的通信问题;
表示为:Student 资源;SetThread 生产线程以及GetThread 消费线程。
void wait ()线程等待
void notify()唤醒等待的单个线程;

生产线程生产好资源后,通知消费线程消费,与此同时再次和消费争抢时间片,但是此时标记为true,表示有资源,就会等待,并释放锁;从而让消费线程消费;依次循环

public class MyTest {
    public static void main(String[] args) {
        //共享资源
        Student student = new Student();
        //生产线程
        SetThread setThread = new SetThread(student);
        //消费线程
        GetThread getThread = new GetThread(student);
        //启动线程
        setThread.start();
        getThread.start();
       
    }
}
class Student {  //资源
    public String name;
    public int age;
    public boolean flag=false; //false代表没有资源,true代表有资源
}
class SetThread  extends Thread{
    Student student;
    int i=0;
    public SetThread(Student student) {
        this.student=student;
    }

    //生产线程:当我生产出一个资源时,等待着,并通知消费者消费
    @Override
    public void run() {
        while (true){
            
            synchronized (student){
                if(student.flag){ //表示有资源
                    try {
                        student.wait(); //等待,释放锁。从哪里等待,被唤醒后,就从这里醒来
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (i % 2 == 0) {
                    student.name = "张三"; 
                    student.age = 23;  
                } else {
                    student.name = "李四";
                    student.age = 24;
                }
                
                //有资源了,通知消费者去消费
                student.flag=true; //修改标记
                student.notify(); //唤醒消费线程,通知后,两个再次抢占时间片
            }

            i++;
        }
    }
}
class GetThread extends Thread{
    Student student;
    public GetThread(Student student) {
        this.student=student;
    }
    //消费线程:消费了资源,等待着,并通知生产者去生产
    @Override
    public void run() {
        while (true){
            synchronized (student){
                if(!student.flag){ //消费者:没有资源等待
                    try {
                        student.wait(); //等待:wait()方法,一旦等待,就要释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //消费
                System.out.println(student.name + "===" + student.age);
                //通知
                student.flag=false; //修改标记
                student.notify();//通知生产者生产,两个线程再次争抢时间片
            }

        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值