写完运行后发现有漏洞,那位大神帮分析分析??
/*
* 多线程的通信
* 输入线程赋值
* 输出线程打印值
*/
//资源对象
class Resource{
String name;
String sex;
boolean b = false;//定义,b=true,赋值完成,b = false打印完成
}
//定义输入线程
class Input implements Runnable{
Resource r ;
Input(Resource r){this.r = r;}
public void run(){
int x = 0 ;
while(true){
synchronized(r){
//输入线程,判断b的值,如果是真,等待
if(r.b==true)
try{r.wait();}catch(Exception e){}
if(x%2==0){
r.name = "张三";
r.sex = "男";
}else{
r.name = "lisi";
r.sex = "nv";
}
x++;
//标记改成true
r.b = true;
//唤醒输出线程
r.notify();
}
}
}
}
//定义输出线程,打印变量值
class Output implements Runnable{
Resource r ;
Output(Resource r){this.r = r;}
public void run(){
while(true){
synchronized(r){
if(r.b==false)
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"..."+r.sex);
r.b = false;
r.notify();
}
}
}
}
public class ThreadDemo6 {
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();
}
}
|
|