线程等待与唤醒案例

定义资源类:

/*
 * 定义资源类,有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();
            }
        }
    }

}

扫描二维码关注公众号,回复: 11278552 查看本文章


测试类:

/*
 * 开启输入线程和输出线程,实现赋值和打印值
 */
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();
    }
}




猜你喜欢

转载自blog.csdn.net/summoxj/article/details/80859777