package p1;
public class Persons {
private String name;
private String sex;
private boolean flag;
public synchronized void setName(String name,String sex) throws InterruptedException
{
if(flag)
{
this.name=name;
this.sex=sex;
flag=false;
this.notify();
}
else
this.wait();
}
public synchronized void show() throws InterruptedException
{
if(!flag)
{
System.out.println(name+" "+sex);
flag=true;
this.notify();
}
else
{
this.wait();
}
}
}
public class You {
public static void main(String[] args) {
Persons p=new Persons();
Thread t1=new Thread(new One(p));
Thread t2=new Thread(new Two(p));
t1.start();
t2.start();
}
}
class One implements Runnable
{
Persons p;
One(Persons p)
{
this.p=p;
}
int n=0;
public void run()
{
while(true)
{
if(n==0)
{
try {
p.setName("li", "nann");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
try {
p.setName("往往冯绍峰", "的份上辐射防护");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
n=(n+1)%2;
}
}
}
class Two implements Runnable
{
Persons p;
Two(Persons p)
{
this.p=p;
}
public void run()
{
while(true)
{
try {
p.show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
为什么得到的结果还是不能实现同步(输入一个,输出一个)呢 |
|