【问题标题】:different synchronized() parameters producing differnt answers [closed]不同的同步()参数产生不同的答案[关闭]
【发布时间】:2014-02-04 09:38:01
【问题描述】:

synchronized(classname.class) vs synchronized(this) vs synchronized(AnyObjectName) 有什么区别?
当同步块只需要任何对象时,为什么这三个都会产生不同的答案?

【问题讨论】:

  • 他们根本不产生答案 - 他们获得监视器,但他们会获得不同的监视器,因为它们是不同的参考。你需要很多清楚你在问什么。
  • 当我在这三个类中添加一个自增运算符时,它们应该会产生相同的结果
  • 信息还不够。我们不知道您是否有多个线程试图增加相同的变量,这些变量可能会或可能不会被每个同步块保护。

标签: java multithreading


【解决方案1】:

synchronized(this)是在当前对象上同步的,所以每个实例只有一个线程可以访问,但是不同的线程可以访问不同的实例。例如。每个线程可以有一个实例。

synchronized(SomeClass.class) 在当前对象的类(或其他类,如果需要)上同步,因此只有一个线程可以访问该类的任何实例。

synchronized(classname.class)的使用

    public class MyClass {

        public static synchronized void log1(String msg1, String msg2){
           log.writeln(msg1);
           log.writeln(msg2);
        }


        public static void log2(String msg1, String msg2){
           synchronized(MyClass.class){
              log.writeln(msg1);
              log.writeln(msg2);  
           }
        }
   }

只有一个线程可以同时在这两种方法中的任何一种中执行。

如果第二个同步块在与 MyClass.class 不同的对象上同步,则一个线程可以同时在每个方法内执行。

【讨论】:

    【解决方案2】:

    Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.

    When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

    因此,在同步块中,您可以显式指定锁。在同步方法中,默认情况下“this”是锁。对于静态同步方法,'CalssName.class' 是锁。

    来自:Intrinsic Locks and Synchronization

    【讨论】:

      猜你喜欢
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      相关资源
      最近更新 更多