同步不同类(和不同包)中的两个方法 [英] Synchronize two methods in different classes (and different packages)

查看:177
本文介绍了同步不同类(和不同包)中的两个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了有关Java方法同步的问题。我希望我能简单解释一下:

I'm facing an issue regarding Java method synchronization. Let's hope I can explain it briefly:

我在两个不同的包中有两种不同的方法。类似于:

I have two different methods in two different classes, in two different packages. Something like:

Package1
     |_Class1
            \MethodA

Package2
     |_Class2
            \MethodB

好的,现在我需要同步这两种方法是非线程。到目前为止,我有两种不同的方法:

Ok, so now I need to synchronize these two methods, which are not threads. So far, I have two different approaches:

共享信号量

Shared semaphore.

Package1 Package2 之外创建共享静态信号量,类似于:

Create a shared static semaphore outside Package1 and Package2, something like:

 package Package3;

 public class SemaphoreClass {

    public static Semaphore;

}

我真的不知道JVM是否会认为这是一个无论如何,共享信号量。

I don't really know if JVM would consider this a shared semaphore, anyway.

同步(SharedClass.class)

Synchronized (SharedClass.class).

使用共享类来同步这两种方法,例如:

Using a shared class to synchronize those two methods, something like:

 public void MethodA() {
        synchronized (SharedClass.class) {
           //...
        }

public void MethodB() {
        synchronized (SharedClass.class) {
           //...
        }

无论如何,这些只是方法。我想知道实现我想要实现的目标的最佳方法是什么。拥有JVM的共享信号量会使事情变得更容易,但是,我知道必须有一个解决方案。在此先感谢。

Anyway, these are just approaches. I would like to hear what's the best way to implement what I'm trying to achieve. Having a shared semaphore for JVM would make things easier, but well, I know there must be a solution for this. Thanks in advance.

推荐答案

您的两种方法都应该有效,但我不认为锁定课程是推荐的做法。首选锁定 Object 的实例,或使用 java.util 中的正确锁定。另外,不要锁定字符串

Both of your approaches should work, but I don't think locking on class is a recommended practices. Prefer locking on instances of Object, or use proper locks from java.util. Also, do not lock on String.

或者,您可以让类的实例 Class1 Class2 可以在实例化期间将锁作为参数:

Alternatively, you could let instances of classes Class1 and Class2 can take a lock as parameter during instantiation:

   class Class1 {
        private final Object lock;
        public Class1( Object lock ) { this.lock = lock }
        public method() { synchronize( lock ) { } );
   }

然后确保创建一个锁(使用 new Object())并将其传递给 Class1 Class2 <的两个实例/ code>。

Then make sure that you create one lock (with new Object()) and pass it to the two instances of Class1 and Class2.

所以基本上,你把原来的问题分解为两个:1)这两个类没有静态地共享任何东西,它们只是接收一个参数。 2) Class1 Class2 的客户必须传递正确的锁。 Class1 Class2 的客户端充当orchestrator。

So basically, you've broken down the original problem in two: 1) the two classes do no share anything statically global, they just receive a parameter. 2) the clients of Class1 and Class2 must pass the correct lock. The client of Class1 and Class2 acts as the "orchestrator".

这篇关于同步不同类(和不同包)中的两个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆