java 如何在 Android 中创建锁 (concurrent.locks.Lock)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14186912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:24:06  来源:igfitidea点击:

How do I create a Lock (concurrent.locks.Lock) in Android?

javaandroidlocking

提问by Neil Townsend

This must be really obvious, but I can't spot the answer. I need to put a lock around a variable to ensure that a couple of race-hazard conditions are avoided. From what I can see, a pretty simple solution exists using Lock, according to the android docs:

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

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

So far, so good. However, I can't make the first line work. It would seem that something like:

到现在为止还挺好。但是,我无法使第一行工作。似乎是这样的:

Lock l = new Lock();

Might be correct, but eclipse reports, "Cannot instantiate the type Lock" - and no more.

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

Any suggestions?

有什么建议?

回答by A--C

If you're very keen on using a Lock, you need to choose a Lockimplementation as you cannotinstantiate interfaces. As per the docsYou have 3 choices:

如果您非常热衷于使用 a Lock,则需要选择一个Lock实现,因为您无法实例化接口。根据文档您有 3 个选择:

You're probably looking for the ReentrantLockpossibly with some Conditions

您可能正在寻找ReentrantLock带有一些Conditions的可能

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

这意味着,而不是Lock l = new Lock();你会做:

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).

但是,如果您需要锁定的只是一小部分,那么同步块/方法会更清晰(如@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;
  }
}

回答by Andrey Atapin

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

只是因为它Lock是一个接口,不能被实例化。使用它的子类。