62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
class B
{
Lock lock=new ReentrantLock();
Condition con=lock.newCondition();
void f()
{
lock.lock();
System.out.print(Thread.currentThread().getName());
System.out.println(">>I'm running");
try { con.await(); }
catch(InterruptedException ex)
{
System.out.print(Thread.currentThread().getName());
System.out.println(">>I'm interrupted!");
}
System.out.print(Thread.currentThread().getName());
System.out.println(">>exit!");
}
}
class A extends Thread
{
B b;
A(B b){this.b=b;}
public void run()
{
b.f();
}
}
public class Test
{
public static void main(String[] args)
{
B b=new B();
A a=new A(b);
a.start();
A aa=new A(b);
aa.start();
try{Thread.sleep(1000);}
catch(InterruptedException ex){/*Deal with it!*/}
a.interrupt();
aa.interrupt();
}
}
void f()
{
lock.lock();
System.out.print(Thread.currentThread().getName());
System.out.println(">>I'm running");
try {con.await(); }
catch(InterruptedException ex)
{
System.out.print(Thread.currentThread().getName());
System.out.println(">>I'm interrupted!");
}
finally
{
lock.unlock(); //释放锁.
}
}