线程等待与唤醒案例

定义资源类:

/*
 * 定义资源类,有2个成员变量
 * name,sex
 * 同时有2个线程,对资源中的变量操作:1个对name,age赋值;2个对name,age做变量的输出打印
 */
public class Resource {
    public String name;
    public String sex;
    public boolean flag=false;

}


InputThread类实现Runnable:

/*
 * 输入的线程,对资源对象Resource中成员变量赋值
 * 一次赋值:张三,男;下一次赋值:李四,女
 */
public class InputThread implements Runnable {
    private Resource r;
    
    public InputThread(Resource r){
        this.r=r;
    }
    
    public void run() {
        int i=0;
        while(true){
            synchronized (r) {
                //标记是true,等待
                if(r.flag){
                    try{
                        r.wait();
                    }catch(Exception ex){}
                }
                if(i%2==0){
                    r.name="张三";
                    r.sex="男";
                }else{
                    r.name="lisi";
                    r.sex="女";
                }
                //将对方线程唤醒,标记改为true
                r.flag=true;
                r.notify();
            }
            i++;
        }
    }

}


OutputThread类实现Runnable:

/*
 * 输出线程,对资源对象Resource中的成员变量,输出值
 */
public class OutputThread implements Runnable {
    private Resource r;
    
    public OutputThread(Resource r){
        this.r=r;
    }
    
    public void run() {
        while(true){
            synchronized (r) {
                //判断标记,是false,等待
                if(!r.flag){
                    try {
                        r.wait();
                    } catch (Exception ex) {}
                }
                System.out.println(r.name+"..."+r.sex);
                //标记改为false,唤醒对方线程
                r.flag=false;
                r.notify();
            }
        }
    }

}


测试类:

/*
 * 开启输入线程和输出线程,实现赋值和打印值
 */
public class ThreadDemo {
    public static void main(String[] args) {
        Resource resource=new Resource();
        
        InputThread in=new InputThread(resource);
        OutputThread out=new OutputThread(resource);
        
        Thread tin=new Thread(in);
        Thread tout=new Thread(out);
        
        tin.start();
        tout.start();
    }
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值