Java 显式锁
2018-02-28 15:45 更新
Java线程教程 - Java显式锁
显式锁定机制可以用于协调对多线程环境中的共享资源的访问。
在java.util.concurrent.locks包中声明的Lock接口定义了显式锁定操作。
ReentrantLock类在同一个包中,是Lock接口的具体实现。
Lock接口声明如下:
public interface Lock { void lock(); Condition newCondition(); void lockInterruptibly() throws InterruptedException; boolean tryLock(); boolean tryLock(long time, TimeUnit unit) throws InterruptedException; void unlock(); }
lock()方法获取一个锁的行为与使用synchronized关键字相同。
我们必须在完成锁定后通过调用Lock接口的unlock()方法释放锁定。
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Main { // Instantiate the lock object private Lock myLock = new ReentrantLock(); public void updateResource() { try { // Acquire the lock myLock.lock(); } finally { // Release the lock myLock.unlock(); } } }
例子
下面的代码模拟哲学家,假设ReentrantLock类的一个对象表示一个fork。
import java.util.concurrent.locks.Lock; class Philosopher { private Lock leftFork; private Lock rightFork; private String name; // Philosopher"s name public Philosopher(Lock leftFork, Lock rightFork, String name) { this.leftFork = leftFork; this.rightFork = rightFork; this.name = name; } public void think() { System.out.println(name + " is thinking..."); } public void eat() { if (leftFork.tryLock()) { try { if (rightFork.tryLock()) { try { System.out.println(name + " is eating..."); } finally { rightFork.unlock(); } } } finally { leftFork.unlock(); } } } }
例2
ReentrantReadWriteLock类是ReadWriteLock接口的实现。只有一个线程可以保持ReentrantReadWriteLock的写锁,而多个线程可以保持其读锁。
下面的代码演示了ReentrantReadWriteLock的用法。
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Main { private int value; private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private Lock rLock = rwLock.readLock(); private Lock wLock = rwLock.writeLock(); public Main(int value) { this.value = value; } public int getValue() { rLock.lock(); try { return this.value; } finally { rLock.unlock(); } } public void setValue(int value) { wLock.lock(); try { this.value = value; } finally { wLock.unlock(); } } }
以上内容是否对您有帮助:
更多建议: