class Resource
{
private boolean flag;
private String name;
private String sex;
public synchronized void set(String name,String sex)
{
if (flag)
{
try
{
this.wait();
}
catch (Exception e){}
}
else
{
this.name= name;
this.sex= sex;
flag= true;
this.notify();
}
}
public synchronized void out()
{
if (!flag)
{
try
{
this.wait();
}
catch (Exception e){}
}
else
{
System.out.println("姓名:"+this.name+" 性别:"+this.sex);
flag= false;
this.notify();
} }
}
class Input implements Runnable
{
private Resource r;
Input(Resource r)
{
this.r= r;
}
public void run()
{
int x= 1;
while (true)
{
if (x==1)
{
r.set("mike","man-------");
}
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.out();
}
}
}class InputOutputDemo3
{
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();
}
}
{
private boolean flag;
private String name;
private String sex;
public synchronized void set(String name,String sex)
{
if (flag)
{
try
{
this.wait();
}
catch (Exception e){}
}
else
{
this.name= name;
this.sex= sex;
flag= true;
this.notify();
}
}
public synchronized void out()
{
if (!flag)
{
try
{
this.wait();
}
catch (Exception e){}
}
else
{
System.out.println("姓名:"+this.name+" 性别:"+this.sex);
flag= false;
this.notify();
} }
}
class Input implements Runnable
{
private Resource r;
Input(Resource r)
{
this.r= r;
}
public void run()
{
int x= 1;
while (true)
{
if (x==1)
{
r.set("mike","man-------");
}
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.out();
}
}
}class InputOutputDemo3
{
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();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货