今天在写线程间的关系代码的时候发现代码一直没有运行成想象中的样子。
发现是if-else之间的关系没有处理好。
class Test1 { boolean flag=false; void xx() { while(true) { if(flag) { System.out.println("1");; }
/*
else
{
System.out.println("2"); 这里else的话 输出是1111111 因为if判断完就不做else判断。
}
*/ System.out.println("2"); //输出是12121212 flag=true; } } } public class Test { public static void main(String[] args) { Test1 t=new Test1(); t.xx(); } }
所以同理;
class Resource
{
String name;
String sex;
boolean flag=false; //判断里面是否有数
}
class Input implements Runnable
{
Resource r;
Input(Resource r)
{
this.r=r;
}
public void run()
{
int i=0;
while(true)
{
synchronized(r)
{
if(r.flag) //没有数据的时候进行输入
{
try {
r.wait();
} catch (InterruptedException e) {
}
}
这里用else和没有用else的区别仔细思考:
if(i==0)
{
r.name="王二锤";
r.sex="男男男男";
//System.out.println(Thread.currentThread().getName());
}
else
{
r.name="李大妞";
r.sex="女女";
//System.out.println(Thread.currentThread().getName());
}
r.flag=true;
r.notify();
}
i=(i+1)%2;
}
}
}
class Output implements Runnable
{
Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
{
try {
r.wait();
} catch (InterruptedException e) {
}
}
//这里若有else会怎么样
System.out.println(r.name+"..."+r.sex+Thread.currentThread().getName());
r.flag=false;
r.notify();
}
}
}
}
public class Demo
{
public static void main(String []args)
{
Resource r=new Resource();
Input in=new Input(r);
Output ou=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(ou);
t1.start();
t2.start();
}
}