鎖定為同步輔助
在 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 文件