lock()方法加锁,unlock()方法释放锁。
tryLock(long time, TimeUnit unit)方法和tryLock()方法是类似的,只不过区别在于这个方法在拿不到锁时会等待一定的时间,在时间期限之内如果还拿不到锁,就返回false。如果一开始拿到锁或者在等待期间内拿到了锁,则返回true。
tryLock()方法是有返回值的,它表示用来尝试获取锁,如果获取成功,则返回true,如果获取失败(即锁已被其他线程获取),则返回false,这个方法无论如何都会立即返回。在拿不到锁时不会一直在那等待。
public class AttemptLocking {
private ReentrantLock lock=new ReentrantLock();
public void untimed(){
boolean captured=lock.tryLock();
try {
System.out.println("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("tryLock(2,TimeUtil.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();
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();
al.untimed();
al.timed();
}
}
效果:
tryLock():true
tryLock(2,TimeUtil.SECONDS): true
acquired
tryLock():false
tryLock(2,TimeUtil.SECONDS): false