本文介绍了Java与多个对象/锁的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个包或模型可以帮助我解决这种情况。



假设我有3个线程和一堆对象A,B ,C,D,E,F




  • T1需要锁A,B

  • B,C,D

  • T3需要锁E,F



如果T1& T3同时运行。此外,T2& T3可以同时运行。但T1&




  • 线程可以获得任意数量的锁,而不只是2.(我看到一个优雅的解决方案这个问题与固定数量的锁,但不确定我可以应用它在这里。)

  • 显然, d喜欢每个线程同时获取所有需要的锁,以防止死锁。



如果有人可以指定一个包支持这个用例,或解析这个的一些代码段,请让我知道。



非常感谢。

解决方案

步骤1



为您的资源提供自然顺序。例如,如果您的资源是字母, A 会出现在 B code>会出现在 C 之前,等等。





现在你的线程不可能在任何时候达到死锁




  • 线程1需要锁定资源 A B D code> E

  • 线程2需要锁定资源 B E



我们的线程必须争夺资源上的锁 B D 。因为我们强制执行一个自然顺序,首先获得 B 锁的线程保证获得 D 并顺利进行。失败的线程将等待 B 被释放。


I'm wondering if there's a package or model that will help me solve this scenario.

Let's say I have 3 threads and a bunch of objects A,B,C,D,E,F

  • T1 needs locks A,B
  • T2 needs locks B,C,D
  • T3 needs locks E,F

In this scenario, it'd be ok if T1 & T3 ran simultaneously. Also, T2 & T3 can run simultaneously. But T1 & T2 should never run simultaneously.

Also, note that

  • Threads can obtain an arbitrary number of locks, not just 2. (I saw an elegant solution to this problem with a fixed number of locks but not sure I can apply it here.)
  • Obviously, I'd like each thread to acquire all the needed locks at the same time to prevent deadlock.

If someone can point me to a package that supports this use case, or some snippet of code that resolves this, please let me know.

Thanks so much.

解决方案

Step 1

Provide a natural ordering for your resources. For example, if your resources were letters, A would come before B, B would come before C, and so on.

Step 2

Only allow your threads to grab resources in order.

Now your threads cannot possibly reach deadlock in any situation.

Example

  • Thread 1 needs locks on resources A, B, D, and E
  • Thread 2 needs locks on resources B and E

Our threads must fight for locks on resources B and D. Because we have enforced a natural order, the thread that obtains the lock on B first is guaranteed to get the lock on D and proceed smoothly. The losing thread will be waiting for B to be released.

这篇关于Java与多个对象/锁的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:56