class InperOurperDemo
{
public static void main(String[] args)
{
Res r = new Res();
Thread t1 = new Thread(new Inper(r));
Thread t2 = new Thread(new Ourper(r));
t1.start();
t2.start();
}
}
class Res
{
String name;
String sex;
boolean flag;
}
class Inper implements Runnable
{
private Res r;
Inper(Res r)
{
this.r = r;
}
public void run()
{
int x=0;
while(true)
{
if (r.flag)
{
try{r.wait();} catch(Exception e){}
}
synchronized(r)
{
if (x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name= "丽丽";
r.sex= "女女女女女女";
}
x=(x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
class Ourper implements Runnable
{
private Res r;
Ourper(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
if(!r.flag)
{
try{r.wait();}catch(Exception e){}
}
synchronized(r)
{
System.out.println(r.name+"........"+r.sex);
r.flag = false;
r.notify();
}
}
}
}作者: 丁桂松 时间: 2012-12-6 00:29
指向的是2个对象.不是同一个对象.无法获得多线程并发访问.无法交替打印.必须是按顺序结构执行语句.作者: 李培根 时间: 2012-12-6 07:36
class InperOurperDem
{
public static void main(String[] args)
{
Res r = new Res();
Thread t1 = new Thread(new Inper(r));
Thread t2 = new Thread(new Ourper(r));
t1.start();
t2.start();
}
}
class Res
{
String name;
String sex;
boolean flag;
}
class Inper implements Runnable
{
private Res r;
Inper(Res r)
{
this.r = r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(r){
if (r.flag) //要定义在同步中,因为要明确操作的是哪个锁上的线程
{
try{r.wait();} catch(Exception e){}
}