class LockConditionDemo
{
public static void main(String[] args)
{
Commander c = new Commander();
SoldierA a = new SoldierA(c);
SoldierB b = new SoldierB(c);
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
Thread t3 = new Thread(b);
Thread t4 = new Thread(b);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Commander
{
String name ;
int day = 1;
boolean flag = false ;
Lock lock = new ReentrantLock();
Condition A = lock.newCondition();//就这里,java中怎么实现的,求解释
Condition B = lock.newCondition();
public void Awork(String name)throws InterruptedException
{
Lock.lock();
try
{
while(flag)
B.await();
this.name = name+"---"+day++;
System.out.println(Thread.currentThread().getName()+"--上半夜站岗--"+this.name);
flag = false ;
A.signal();
}
finally
{
lock.unlock()
}
}
public void Bwork(String name)throws InterruptedException
{
try
{
while(!flag)
B.await();
this.name = name+"---"+day++;
System.out.println(Thread.currentThread().getName()+"------下半夜站岗------"+this.name);
flag = false ;
A.signal();
}
finally
{
lock.unlock()
}
}
}
class SoldierA implements Runnable
{
private Commander com;
SoldierA(Commander com)
{
this.com = com ;
}
public void run()
{
while (true)
{
try
{
com.Awork("小强");
}
catch (InterruptedException e)
{
}
}
}
}
class SoldierB implements Runnable
{
private Commander com;
SoldierB(Commander com)
{
this.com = com ;
}
public void run()
{
wwhile (true)
{
try
{
com.Bwork("大黄");
}
catch (InterruptedException e)
{
}
}
}
} |