/*线程通信代码改进和优化
* 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();
}
}
|
|