线程等待和唤醒题目

线程等待和唤醒题目

描述:

使用等待唤醒,实现一个线程给共享对象Person的属性(姓名,性别)赋值,一个线程打印共享对象的属性要求赋值-

>打印->赋值->打印 ... 不允许出现人妖

测试类:

/**
 使用等待唤醒,实现一个线程给共享对象Person的属性(姓名,性别)赋值,
 一个线程打印共享对象的属性要求赋值->打印->赋值->打印 ... 不允许出现人妖.
 */
public class Demo01 {
    public static void main(String[] args) {
        // 创建共享资源对象
        Person p = new Person();
        // 创建输入线程
        Thread tin = new Thread(new InputThread(p),"输入线程");
        // 创建输出线程
        Thread tout = new Thread(new OutputThread(p),"输出线程");
        // 开启线程
        tin.start();
        tout.start();
    }
}

输入线程:

public class InputThread implements Runnable {
    private Person p;

    public InputThread(Person p) {
        this.p = p;
    }

    @Override
    public void run() {
        int index = 0;
        while(true) {
            synchronized (p) {
                // 给对象属性赋值
                if(index % 2 == 0 ) {
                    p.name = "张三";
                    p.sex = "男";
                } else {
                    p.name = "lisi";
                    p.sex = "nv";
                }
                // 设置标记为true
                p.flag = true;
                // 唤醒输出线程
                p.notify();
                try {
                    // 等待输出线程输出
                    p.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            index ++;
        }
    }
}

输出线程:

public class OutputThread implements Runnable {
    private Person p;
    public OutputThread(Person p) {
        this.p = p;
    }
    @Override
    public void run() {
        while(true){
            synchronized (p) {
                try {
                    if(p.flag) {
                        // 输出内容
                        System.out.println(Thread.currentThread().getName() + p);
                        // 设置标记为false
                        p.flag = false;
                        // 唤醒输入线程
                        p.notify();
                    }
                    // 进入等待状态
                    p.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

实体类:

public class Person {
    public String name;
    public String sex;
    public boolean flag;
    @Override
    public String toString() {
        return " name=" + name + ", sex=" + sex;
    }
}

posted @ 2020-06-13 11:02  阿亮在努力  阅读(249)  评论(0)    收藏  举报