package ResourceDemo;
class Resource
{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(String name,String sex)
{
if(flag)
{
try{this.wait();}catch(InterruptedException e){}
}
// else
// {
this.name = name;
this.sex = sex;
flag=true;
notify();
// }
}
public synchronized void get()
{
if(!flag)
{
try{this.wait();}catch(InterruptedException e){}
}
else
{
System.out.println(name+"...+..."+sex);
flag=false;
notify();
}
}
}
class Input implements Runnable
{
private Resource r;
Input(Resource r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
r.set("Siling","Nan");
else
r.set("司令","女");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.get();
}
}
}
public class ResourceDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
Input a=new Input(r);
Output b=new Output(r);
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t1.start();
t2.start();
}
}
学习多线程,仿照教程敲的代码。flag的作用就是让两个输出语句间隔输出。
上面加注释的else部分,如果有else,就会出现两条语句分别一片一片输出的情况,如果没有else,就正常两条语句分别间隔输出。
可是有没有else理论上有影响吗?