多线程-等待与唤醒

等待  与  唤醒

1、wait():让线程处于冻结状态,被wait的线程会被存储到线程池里

2、notify():唤醒线程池里任意一个线程

3、notifyAll():唤醒线程池里所有的线程。

这些方法都必须定义在同步中,因为这些方法是用于操作线程状态的方法,必须要明确到底操作的是那个锁上的线程

为什么操作线程的方法 wait notifh notifyAll 定义在Object类中,因为这些方法是监视器的方法,而监视器就是锁。

//这个是资源类
public class Resources {
    private String name;
    private String work;
    private boolean flag = false;
    public synchronized void set(String name,String work){
        if(this.flag)
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.name = name;
            this.work = work;
            this.flag = true;
            this.notify();
    }
    public synchronized void qu(){
        if(!this.flag)
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("姓名:"+name+",工作:"+work);
            this.flag = false;
            this.notify();
    }
}

 

//这个事负责向资源类里存东西的,当资源类里有东西时候就等待,没有的时候就存

public class Input implements Runnable{
    Resources r;
    public Input(Resources r){
        this.r = r;
    }
    @Override
    public void run() {
        int num = 0;
        while (true){
            if(num == 0){
                r.set("张三","java");
            }else {
                r.set("笑话","php");
            }
            num = (num+1)%2;
        }
    }
}

//这个是出东西的类,当没有时候就等待,有的时候就打印

public class Output implements Runnable{
    Resources r;
    public Output(Resources r){
        this.r = r;
    }
    @Override
    public void run() {
        while (true){
            r.qu();
        }
    }
}

//测试函数

public class Test4 {
    public static void main(String[] args){
        Resources r = new Resources();
        Input i = new Input(r);
        Output o = new Output(r);
        Thread t = new Thread(i);
        Thread tt = new Thread(o);
        t.start();
        tt.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值