本帖最后由 戎石锁 于 2012-8-13 22:50 编辑
class InOutDemo
{
public static void main(String[] args)
{
Res r= new Res();
In in = new In(r);
Out out=new Out(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Res
{
String name;
String sex;
public boolean flag=false;
}
class In implements Runnable
{
private Res r;
In(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(In.class)
{
if(r.flag)
try{r.wait();}catch(Exception e){}
if(x==0)
{
r.name="第一线程";
r.sex="第一线程 第一线程";
}
else
{
r.name="dierxiancheng";
r.sex="dierxaincheng";
}
x=(x+1)%2;
r.flag=true;
r.notify();
}
}
}
}
class Out implements Runnable
{
private Res r;
Out(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(In.class)
{
if(!r.flag)
{
try{r.wait();}catch (Exception e){} //In.wait();为什么不能用In,我已经定义了一个In类
System.out.println(Thread.currentThread().getName()+r.name+" "+r.sex);
r.flag=false;
r.notify(); //In.notify();为什么不能用In,我已经定义了一个In类 }
}
}
}问题是:
看老毕视频,说在等待唤醒机制中,wait()方法必须表示出它操作那个线程所属的锁,我的锁是In.class,
但是In.wait();编译无法通过
}
|
|