package anquan;
public class anquan
{
public static void main(String[]args)
{
A a=new A();
in b=new in(a);
out c=new out(a);
Thread t1=new Thread(b);
Thread t2=new Thread(c);
t1.start();
t2.start();
}
}
class A
{
boolean n=false;
public String name;
public String sex;
}
class in implements Runnable
{
private A a;
in(A a)
{
this.a=a;
}
boolean b=true;
public void run()
{
while(true)
{
synchronized(a)
{
if(a.n)
try{a.wait();}catch(Exception e){}
if(b)
{
a.name="张三";
a.sex="男男男";
b=false;
}
else
{
a.name="李四";
a.sex="女女女女";
b=true;
}
a.n=true;
a.notify();
}
}
}
}
class out implements Runnable
{
private A a;
out(A a)
{
this.a=a;
}
public void run()
{
while(true)
synchronized(a){
if(!a.n)
try{a.wait();}catch(Exception e){}//wait()的时候会不会释放锁 如果不释放锁的话 另一个线程就拿不到a这个锁啊 这样的话不就死锁了 吗
System.out.println("name==="+a.name+"======sex====="+a.sex);
a.n=false;
a.notify();
}
}
|