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理论上有影响吗?
问题分几部分,不知道这么讲你能不能懂
1.如果在有else的正常情况下,计数x不管set执不执行,“司令”这个内容是无论如何都输入不进去的。写入(SiLing),停(女),写入(Ling),停(女)
2.如果再没有else的情况下,计数x每次变化都会执行set,且第一次set之后都会阻塞,需要等get成功执行后才能执行赋值,所以是间隔输出
3.如果在有else的非正常情况下,可能发生了set在某次唤醒后,本来是执行 停(女)的操作,但是Flag值被另一个线程又一次改变了,所以成功写入(注意,是可能发生,还可能发生其他情况,和第2个情况不同是因为第二个情况是每次都执行set,没有方法的再次调用过程)
有 else的话,就是交替执行,没有else的话就是每次都执行赋值。