package cn.test.thread;
class Resource {
private String name;
private String sex;
boolean flag = false;
public synchronized void set(String name,String sex){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {//这里加了个else之后,输出的结果不是想要的那种。去掉else,即可。可是为什么呢?请教大神!
this.name = name;
this.sex = sex;
this.notify();
this.flag = true;
}
}
public synchronized void out(){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println(name+"..."+sex);
this.notify();
this.flag = false;
}
}
}
/**
* 资源输入
* @author sea
*
*/
class Input implements Runnable{
Resource r;
public Input(Resource r){
this.r = r;
}
@Override
public void run() {
int num = 0;
while(true){
if(num == 0){
r.set("张三","男");
//System.out.println(Thread.currentThread().getName()+"资源输入");
}else{
r.set("lili", "female");
//System.out.println(Thread.currentThread().getName()+"资源输入");
}
num = ++num%2;
}
}
}
class Output implements Runnable{
Resource r ;
public Output(Resource r){
this.r = r;
}
@Override
public void run() {
while(true){
r.out();
}
}
}
public class InformationTest {
public static void main(String[] args) {
Resource r = new Resource();
Input ip = new Input(r);
Output op = new Output(r);
Thread t1 = new Thread(ip);
Thread t2 = new Thread(op);
t1.start();
t2.start();
}
}
------解决思路----------------------
我的看法,楼主参考:
问题就是当wait()结束后,程序从哪接着执行?正常情况下,wait()结束,应该执行else语句块里的内容,但你把它放在else里,它就不执行了,跳过了赋值语句。
另外,这种情况下最好用while,不用if,某些场合会出问题。