15

这一定很明显,但我找不到答案。我需要锁定一个变量,以确保避免几个竞争危险情况。根据 android 文档,据我所知,使用 Lock 存在一个非常简单的解决方案:

Lock l = ...;
l.lock();
try {
    // access the resource protected by this lock
 }
 finally {
     l.unlock();
 }

到目前为止,一切都很好。但是,我无法使第一行工作。似乎是这样的:

Lock l = new Lock();

可能是正确的,但 Eclipse 报告“无法实例化类型锁定” - 仅此而已。

有什么建议么?

4

2 回答 2

17

If you're very keen on using a Lock, you need to choose a Lock implementation as you cannot instantiate interfaces. As per the docs You have 3 choices:

You're probably looking for the ReentrantLock possibly with some Conditions

This means that instead of Lock l = new Lock(); you would do:

ReentrantLock lock = new ReentrantLock();

However, if all you're needing to lock is a small part, a synchronized block/method is cleaner (as suggested by @Leonidos & @assylias).

If you have a method that sets the value, you can do:

public synchronized void setValue (var newValue)
{
  value = newValue;
}

or if this is a part of a larger method:

public void doInfinite ()
{
  //code
  synchronized (this)
  { 
    value = aValue;
  }
}
于 2013-01-06T21:27:55.810 回答
1

Just because Lock is an interface and can't be instantiated. Use its subclasses.

于 2013-01-06T21:28:23.690 回答