java多线程等待唤醒机制

等待唤醒机制:
Object类中提供了三个方法:
wait():等待
notify():唤醒单个线程
notifyAll():唤醒所有线程
为什么这些方法不定义在Thread类而定义在Object类中呢?
这些方法的调用必须通过锁对象调用,而我们使用的锁对象是任意锁对象。所以,这些方法必须定义在Object类中。

生产者和消费者多线程体现(线程间通信问题)
生产者:先看是否有数据,有就等待;没有就生产并通知消费者消费
消费者:先看是否有数据,有就消费;没有就等待并通知生产者生产
资源类:Student
设置数据类:SetStudent(生产者)
获取数据类:GetStudent(消费者)
测试类:StudentDemo

public class Student {

    String name;
    int age;
    boolean flag;

}
public class SetStudent implements Runnable {
    private Student s;
    private int x=0;
    public SetStudent(Student s) {
        this.s=s;
    }

    public void run() {
        while(true){
            synchronized (s) {
                if(s.flag){
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(x%2==0){
                    s.name="huge";
                    s.age=20;
                }else{
                    s.name="allen";
                    s.age=21;
                }
                x++;
                s.flag=true;
                s.notify();
            }
        }
    }
}
public class GetStudent implements Runnable {
    private Student s;
    public GetStudent(Student s) {
        this.s=s;
    }
    public void run() {
        while(true){
            synchronized (s) {
                if(!s.flag){
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(s.name+s.age);
                s.flag=false;
                s.notify();
            }   
        }
    }
}
public class StudentDemo {
    public static void main(String[] args) {
        Student s=new Student();
        GetStudent gt=new GetStudent(s);
        SetStudent st=new SetStudent(s);
        Thread t1=new Thread(gt);
        Thread t2=new Thread(st);
        t1.start();
        t2.start();

    }
}

输出:

huge20
allen21
huge20
allen21
huge20
allen21
huge20
allen21
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值