/*
* 线程通信的程序进行改造和优化,其实该的地方不多,看了视频才知道~~~
* 成员变量进行私有修饰,提供set get方法
*/
//定义资源对象,成员变量,私有
class Resource{
private String name;
private String sex;
private boolean b = false;
//提供公共的set方法,对变量赋值
public synchronized void set(String name,String sex){
if(b)
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
b = true;
this.notify();
}
//提高公共的get方法,直接打印变量值
public synchronized void get(){
if(!b)
try{this.wait();}catch(Exception e){}
System.out.println(name+".."+sex);
b = false;
this.notify();
}
}
//定义输入线程,负责调用Set方法赋值
class Input implements Runnable{
private Resource r;
Input(Resource r){this.r = r;}
public void run(){
int x = 0 ;
while(true){
if(x % 2 == 0){
r.set("张三", "男");
}else{
r.set("lisi", "nv");
}
x++;
}
}
}
//定义输出线程,负责调用get方法,打印
class Output implements Runnable{
private Resource r;
Output(Resource r){this.r = r;}
public void run(){
while(true)
r.get();
}
}
public class ThreadDemo {
public static void main(String[] args) {
Resource r = new Resource();
Input in = new Input(r);
Output out = new Output(r);
Thread tin = new Thread(in);
Thread tout = new Thread(out);
tin.start();
tout.start();
}
}
|
|