简体   繁体   English

Java并在另一个线程持有锁时通过同步块

[英]java and passing over a synchronized block when another thread's holding the lock

Is it possible to pass over a synchronized block of code when another thread has the synchronized object under lock? 当另一个线程的同步对象处于锁定状态时,是否可以传递同步的代码块? If not, is there an alternative that can act in this way? 如果没有,是否有其他方法可以以此方式行事?

You can replace the synchronized block with the java.util.concurrent.locks.ReentrantLock class. 您可以将synchronized块替换为java.util.concurrent.locks.ReentrantLock类。 This class provides very similar mutual exclusion features, but it also has the method tryLock , which acquires the lock if it's free, or returns false immediately if it's taken. 此类提供了非常相似的互斥功能,但它也具有方法tryLock ,如果锁是免费的,则获取该锁;如果使用了锁,则立即返回false。

So you can have something like: 因此,您可以像以下内容:

 private final ReentrantLock rlock = new ReentrantLock();

Code of thread 1: 线程代码1:

 // thread 1 has normal synchronized behavior
 rlock.lock();
 // code
 rlock.unlock();

And thread 2: 和线程2:

 // thread 2 will skip the code if the lock is already taken
 if(rlock.tryLock()) {
     // code
     rlock.unlock();
 }

It can be done with a guard object. 可以使用保护对象来完成。 The guard object has a function that does this: 保护对象具有执行此操作的功能:

  1. Lock the guard object. 锁定防护对象。

  2. Check if the guard flag is set. 检查是否设置了防护标志。 If so, return false , unlocking the guard object. 如果是这样,则返回false ,从而解除保护对象的锁定。

  3. Set the guard flag. 设置防护标志。

  4. Return true , unlocking the guard object. 返回true ,解锁防护对象。

If the caller gets true , it knows it can operate on the guarded object without conflicting with any other threads because only one thread can set the guard flag from false to true until it is set back to false , and other threads only access the object if they have set the guard flag. 如果调用者为true ,则知道它可以在受保护对象上进行操作而不会与任何其他线程发生冲突,因为只有一个线程可以将保护标志从falsetrue直到将其设置为false为止,其他线程仅在以下情况下访问该对象:他们设置了后卫标志。

When done, re-lock the guard object and clear the guard flag to allow other threads in. 完成后,重新锁定防护对象并清除防护标志以允许其他线程进入。

The locking of the guard object can, of course, be implicit through the use of synchronized functions. 当然,可以通过使用同步功能隐含保护对象的锁定。 Usually you don't wind up creating an object just to guard, you fold other functionality associated with why you needed to guard the object into the guard object. 通常,您不会仅仅为了保护对象而创建对象,而是将与为什么需要保护对象相关的其他功能折叠到了保护对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM