锁定为同步辅助
在 Java 5 的并发软件包引入之前,线程化程度较低。此软件包的引入提供了几个更高级别的并发编程辅助/构造。
锁是线程同步机制,其基本上用于与同步块或关键字相同的目的。
内在锁定
int count = 0; // shared among multiple threads
public void doSomething() {
synchronized(this) {
++count; // a non-atomic operation
}
}
使用锁定同步
int count = 0; // shared among multiple threads
Lock lockObj = new ReentrantLock();
public void doSomething() {
try {
lockObj.lock();
++count; // a non-atomic operation
} finally {
lockObj.unlock(); // sure to release the lock without fail
}
}
锁还具有内部锁定不提供的功能,例如锁定但保持对中断的响应,或者尝试锁定,并且在无法锁定时不阻止。
锁定,响应中断
class Locky {
int count = 0; // shared among multiple threads
Lock lockObj = new ReentrantLock();
public void doSomething() {
try {
try {
lockObj.lockInterruptibly();
++count; // a non-atomic operation
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // stopping
}
} finally {
if (!Thread.currentThread().isInterrupted()) {
lockObj.unlock(); // sure to release the lock without fail
}
}
}
}
只有在能够锁定时才能做某事
public class Locky2 {
int count = 0; // shared among multiple threads
Lock lockObj = new ReentrantLock();
public void doSomething() {
boolean locked = lockObj.tryLock(); // returns true upon successful lock
if (locked) {
try {
++count; // a non-atomic operation
} finally {
lockObj.unlock(); // sure to release the lock without fail
}
}
}
}
有几种锁可供选择。有关详细信息,请参阅此处的 api 文档