本文介绍了为什么使用ReentrantLock如果可以使用synchronized(this)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你可以使用 synchronized(this),我想了解什么使得锁的并发性非常重要。在下面的虚拟代码中,我可以做:

I'm trying to understand what makes the lock in concurrency so important if one can use synchronized (this). In the dummy code below, I can do either:


  1. 同步整个方法或同步易受攻击的区域。})

  2. 使用ReentrantLock锁定易受攻击的代码区域。

/ p>

Code:

private final ReentrantLock lock =  new ReentrantLock();
    private static List<Integer> ints;

    public Integer getResult(String name) {
        .
        .
        .
        lock.lock();
        try{
            if (ints.size()==3) {
                ints=null;
                return -9;
            }

            for (int x=0; x<ints.size(); x++) {
                System.out.println("["+name+"] "+x+"/"+ints.size()+". values >>>>"+ints.get(x));
            }

        }finally {
            lock.unlock();
        }
        return random;
}


推荐答案

A 是非结构化的,与<$ c不同$ c> synchronized 构造 - 即,您不需要使用块结构进行锁定,甚至可以跨方法保持锁定。例如:

A ReentrantLock is unstructured, unlike synchronized constructs -- i.e. you don't need to use a block structure for locking and can even hold a lock across methods. An example:

private ReentrantLock lock;

public void foo() {
  ...
  lock.lock();
  ...
}

public void bar() {
  ...
  lock.unlock();
  ...
}

这种流程不可能通过单个监视同步构造。

Such flow is impossible to represent via a single monitor in a synchronized construct.

code> ReentrantLock 支持和。 ReentrantLock 也支持,允许更灵活的线程调度。

Aside from that, ReentrantLock supports lock polling and interruptible lock waits that support time-out. ReentrantLock also has support for configurable fairness policy, allowing more flexible thread scheduling.






code> ReentrantLock 可能也可以,在更高的争用下表现更好。您可以在此了解详情。


ReentrantLock may also be more scalable, performing much better under higher contention. You can read more about this here.

然而,这项索赔受到质疑;请参阅以下注释:

This claim has been contested, however; see the following comment:






何时使用 ReentrantLock s?根据那篇developerWorks文章...


When should you use ReentrantLocks? According to that developerWorks article...

这篇关于为什么使用ReentrantLock如果可以使用synchronized(this)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 23:45