A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

/*线程通信代码改进和优化
*  1. 学生资源成员变量,被修饰私有  提供get set
*  2. 同步技术改进,同步方法实现
*/
class Student{
        private String name;
        private String sex;
        private boolean flag;
        //对于私有成员,提供公共访问方式
        //1个方法set,完成2个变量赋值
        public synchronized void set(String name,String sex){
                //生产者,判断标记,标记是true,等待,不能赋值
                if(flag){
                        try{this.wait();}catch(Exception ex){}
                }
                this.name=name;
                this.sex=sex;
                //赋值完成,变量改成true
                flag=true;
                //唤醒对方线程
                this.notify();
        }
        //1个方法get,完成2个变量输出
        public synchronized void get(){
                //消费者,判断标记,标记是false,等待不能打印
                if(!flag){
                        try{this.wait();}catch(Exception ex){}
                }
                System.out.println(name+"..."+sex);
                //将标记修改成false
                flag=false;
                //唤醒对方线程
                this.notify();
        }
}
//生产者线程
class Product implements Runnable{
        private Student s;
        Product(Student s){this.s=s;}
        public void run(){
                int x = 0 ;
                while(true){
                        if(x%2==0){
                                s.set("张三", "男");
                        }else{
                                s.set("李四", "女");
                        }
                        x++;
                       
                }
        }
}
//定义消费者线程
class Customer implements Runnable{
        private Student s;
        Customer(Student s){this.s=s;}
        public void run(){
                while(true)
                        s.get();
        }
}
public class ThreadDemo1 {
        public static void main(String[] args) {
                 Student s = new Student();
                 new Thread(new Product(s)).start();
                 new Thread(new Customer(s)).start();
        }
}

1 个回复

倒序浏览
路过,打酱油
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马