且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

同步不同类(和不同包)中的两个方法

更新时间:2022-11-24 15:37:01

您的两种方法都应该有效,但我不认为锁定课程是推荐的做法。首选锁定 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 。

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