Lock API文档翻译

来源:互联网 发布:手机怎么关联淘宝小号 编辑:程序博客网 时间:2024/05/17 09:15

Lock是一个接口,英文api中的介绍如下:

Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.
Lock接口提供的同步锁操作比synchronized机制提供的操作多。Lock框架提供的结构很灵活,含有很多种不同的属性,可以支持多个相互联系的Condition对象。(对应的函数比如tryLock,lockInterruptibly,并且可以直接使用newCondition获取多个condition对象来控制各个进程的工作状态。)
A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.
Lock是控制多线程访问公共资源的工具。通常,Lock允许在同一时间只允许一个线程独自获取共享资源的访问权限。然而一些Lock会允许并发访问权限,比如读写锁ReadLock。(后面会贴上代码)
The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.
synchronized关键字修饰的函数或变量给和每个对象联系的互斥的监听器提权限,但是强制这些释放和请求必须发生在快结构中,也就是多个锁在请求的时候,他们必须以相反的顺序释放。并且所有的锁必须在获得锁的作用域中进行释放(就是说获得锁和释放锁的顺序是反的,但是synchronized是自动释放的,而Lock是需要放到finally语句中手动释放。)
While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of “hand-over-hand” or “chain locking”: you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.
尽管synchronized的作用域机制让同步编程变得更加简单,并且帮助避免了很多常见的编程错误,但是仍有一些场景需要更加灵活的方式。例如:一些需要同时进行的算法或者chain-locking,你需要获得A的锁,B的锁,然后释放A的锁,获取C的锁,然后释放B的锁,获取D的锁等等。继承了Lock接口可以让锁在不同的作用域中按任意顺序进行获取和释放。
With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used:
增高的灵活性带来更多的责任。快结构的缺失导致锁不能自动关闭,而synchronized方法则可以。在大部分情况下,下面的语句要有
Lock l = …;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}

When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary.
当lock和unlock在不同的作用域时,必须小心保证所有的代码位于try-finally中,确保锁会在必要的时候释放。
Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).
继承了Lock接口之后会添加很多方法,比如在非块(这里不知如何翻译)中尝试获取锁,可以被打断的锁,限定响应时间的trylock.
A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such specialized semantics then the implementation must document those semantics.
这段太难翻译,也不是很重要,就略过哈。

总而言之,就是可以抛弃synchronized
并发访问例子:

class BoundedBuffer {    final Lock lock = new ReentrantLock();          //锁对象    final Condition notFull  = lock.newCondition(); //写线程锁    final Condition notEmpty = lock.newCondition(); //读线程锁    final Object[] items = new Object[100];//缓存队列    int putptr;  //写索引    int takeptr; //读索引    int count;   //队列中数据数目    //写    public void put(Object x) throws InterruptedException {      lock.lock(); //锁定      try {        // 如果队列满,则阻塞<写线程>        while (count == items.length) {          notFull.await();         }        // 写入队列,并更新写索引        items[putptr] = x;         if (++putptr == items.length) putptr = 0;         ++count;          // 唤醒<读线程>        notEmpty.signal();       } finally {         lock.unlock();//解除锁定       }     }      //读     public Object take() throws InterruptedException {       lock.lock(); //锁定       try {        // 如果队列空,则阻塞<读线程>        while (count == 0) {           notEmpty.await();        }          //读取队列,并更新读索引        Object x = items[takeptr];         if (++takeptr == items.length) takeptr = 0;        --count;        // 唤醒<写线程>        notFull.signal();         return x;       } finally {         lock.unlock();//解除锁定       }     }   
0 0
原创粉丝点击