使用显式的Lock对象
2020-03-09 本文已影响0人
桐桑入梦
package concurrency;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class AttemptLocking {
private ReentrantLock lock = new ReentrantLock();
//尝试获取锁
public void untimed(){
boolean captured = lock.tryLock();
try{
System.out.println( "lock.tryLock() = " + captured );
}finally {
//如果获取了锁,那么需要释放锁
if( captured )
lock.unlock();
}
}
//尝试获取锁一段时间,然后过了时间则放弃锁
public void timed(){
boolean captured = false;
try{
captured = lock.tryLock( 2, TimeUnit.SECONDS );
}catch( InterruptedException e ){
throw new RuntimeException( e );
}
try{
System.out.println( "lock.tryLock( 2, TimeUnit.SECONDS ) = " + captured );
}finally {
if( captured )
lock.unlock();
}
}
public static void main(String[] args) {
final AttemptLocking al = new AttemptLocking();
al.untimed();
al.timed();
//创建一个匿名类
new Thread(){
{ setDaemon( true );} //类似静态域,在创建对象的时候会执行
@Override
public void run(){
al.lock.lock();
System.out.println( "acquired");
}
}.start();
Thread.yield(); //为了给run()方法顺利执行完一个机会
//因为Thread.yield()效果不明显,故睡眠一会
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main Thread after sleeping");
al.untimed();
al.timed();
}
}