什么是java中的类级锁 [英] What is a class level lock in java

查看:113
本文介绍了什么是java中的类级锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是班级锁。你能用一个例子来解释吗。

What is a class level lock. Can you please explain with an example.

推荐答案

我假设你指的是同步锁。如果您不熟悉同步,则可以防止同一代码同时由两个不同的线程运行。在java中,使用Object锁完成同步:

I am assuming you are referring to a synchronization lock. If you are unfamiliar with synchronization it is a means to prevent the same code being run by two different threads at the same time. In java synchronization is done with Object locks:

Object lock = new Object();

public void doSomething(){
  ...
  synchronized(lock){
    //something dangerous
  }
  ...
}

在此代码中,只保证一个线程可以在给定的情况下执行某些危险操作时间,它将完成synchronized块中的所有内容,然后另一个线程可能开始运行相同的代码。我猜你所指的是类级别锁定是对同步方法的隐式锁定:

In this code it is guaranteed only one thread can do something dangerous at a given time, and it will complete everything in the synchronized block before another thread may start running the same code. I am guessing what you are referring to as a "class level lock" is the implicit lock on synchronized method:

public synchronized void somethingDangerous(){...}

这里再次只有一个线程可以在任何给定时间执行该方法并且总是在另一个线程开始执行代码之前完成。这相当于this上的同步块:

Here again only one thread can execute the method at any given time and will always finish before another thread may begin executing the code. This is equivalent to a synchronized block on "this":

public void somethingDangerous(){
  synchronized(this){
    //something dangerous
  }
}

现在这个锁实际上并不在类上,而是在单个实例上(即不是所有时钟,而只是你的时钟)。如果你想要一个真正的类级锁(通常在静态方法中完成),那么你需要在一些独立于任何实例的东西上进行同步。例如:

Now this lock isn't actually on the class, but rather on a single instance (i.e. not all clocks, but only your clock). If you want a true "class level lock" (which would typically be done in a static method), then you need to synchronize on something independent of any instances. For example:

public class Clock{
  private static Object CLASS_LOCK = new Object();

  public static void doSomething(){
    ...
    synchronized(CLASS_LOCK){
      //something dangerous to all clocks, not just yours
    }
    ...
  }
}

再次有静态方法的隐式锁定:

again there is an implicit lock for static methods:

public class Clock{
  public static synchronized void somethingDangerous(){}
}

这相当于锁定类对象:

public class Clock{
  public static void somethingDangerous(){
    synchronized(Clock.class){
      //do something dangerous
    }
  }
}

这篇关于什么是java中的类级锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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