import java.util.concurrent.locks.*;
class Place
{
//Lock c = new ReentrantLock ();
private String name ;
private String sex;
public void set(String name , String sex )
{
this.name = name ;
this.sex=sex ;
System.out.println(Thread.currentThread().getName()+"......"+name );
}
public void out()
{
System.out.println(Thread.currentThread().getName()+"......"+name );
}
boolean y = true ;
}
class InPut implements Runnable
{
private Place r;
private Lock w;
InPut(Place r,Lock w)
{
this.r=r ;
this.w =w;
}
Condition d1= w.newCondition();
int x=0;
public void run() //throws InterruptedException
// 分析出现两次lihai的原因
{
while(true )
{
w.lock();
while (r.y )
try
{
d1.await();
if (x==0 )
r.set ("lihai", "man");
else
r.set("张三","女女");
x=(x+1 )%2;
r.y=true ;
d1.signal();
}
catch (Exception e)
{
}
finally{ w.unlock();
}
}
}
}
class OutPut implements Runnable
{
//Object obj= new Object();
//Lock c = new ReentrantLock ();
private Lock w;
private Place r;
OutPut(Place r,Lock w)
{
this.r=r ;
this.w=w;
}
Condition d2= w.newCondition();
public void run()
{
while (true)
{
w.lock();
while (!r.y )
try
{
d2.await();
r.out();
r.y=false ;
d2.signal();
}
catch (Exception e)
{
}
finally{w.unlock();
}
}
}
}
class LockDemo
{
public static void main(String[] args)
{
Lock c = new ReentrantLock ();
Place p = new Place();
InPut in=new InPut(p,c);
OutPut out = new OutPut(p,c);
Thread t1= new Thread(in );
Thread t2= new Thread(out );
Thread t3= new Thread(in );
Thread t4= new Thread(out );
t1.start();
t2.start();
t3.start();
t4.start();
}
}
程序可以编译通过,但是运行结果提示“空指针异常”!! 我认为问题可能出现在红色代码区域 我这里使用的是锁 而不是同步代码块 求解答~~ |