线程的等待唤醒机制

线程的等待唤醒机制

由于Java 采用抢占式调度,CPU只需要一点点的时间就可以执行很多次,而且线程运行具有随机性,经常会出现数据不匹配的现象,此时Java给出了一种等待唤醒机制来解决这种问题

Object类中提供了三个方法

wait():等待,一旦等待就会释放锁
notify():唤醒单个线程

notifyAll():唤醒所有线程

学生类

package org.westos.demo2;

public class Student {
    private String name;
    private int age;
    private boolean flag=false;
    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();//唤醒之后不是马上执行,而是重新开始抢占
    }
    public synchronized void get(){
        if(!this.flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        //消费
        System.out.println(this.name+"===="+this.age);
        //修改标记并通知
        this.flag=false;
        this.notify();
    }


}

set线程

package org.westos.demo2;

public class Set implements Runnable {
    Student s;
    int i=0;
    public Set(Student s){
        this.s=s;
    }
    @Override
    public void run() {
        while(true){
            if(i%2==0){
                s.set("老大",30);
            }else{
                s.set("老二",20);
            }
            i++;
        }

    }
}

get线程

package org.westos.demo2;

public class Get implements Runnable {
    Student s;

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

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


    }
}

测试类

package org.westos.demo2;

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        Set set = new Set(student);
        Get get = new Get(student);
        Thread tset = new Thread(set);
        Thread tget = new Thread(get);
        tset.start();
        tget.start();
    }
}

效果

老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20
老大====30
老二====20







你可能感兴趣的:(线程的等待唤醒机制)