简体   繁体   English

Lock on class是什么意思?

[英]What does it mean by Lock on class?

If the static synchronized method takes lock on class than what it means. 如果静态同步方法在类上的锁定超过了它的含义。 Does it means that unless the class lock has been released its new object cannot be created. 这是否意味着除非已释放类锁,否则无法创建其新对象。 I tried one program to raplicate this but i found it does not means this than what exactly does lock on class means does it means that all the instances of that class will get locked. 我尝试了一个程序来复制它,但我发现这并不意味着这比对类进行的锁定意味着这意味着该类的所有实例都将被锁定。

public class StsticSyncTest implements Runnable{

public static void main(String[] args) {

    Thread t = new Thread(new StsticSyncTest());
    t.start();
    try {
        Y y = new Y();
        System.out.println(y);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

@Override
public void run() {
    Y y = new Y();
    y.method1();
}

}
class Y{

static synchronized void method1(){
    for(;;){
        //System.out.println("1");
    }
}

}

It gave output: com.nikhil.test.synchronization.Y@cac268 它给出了输出:com.nikhil.test.synchronization.Y@cac268

A synchronized method uses the instance as the lock object. 同步方法将实例用作锁定对象。

A static synchronized method uses the class as the lock object. 静态同步方法将此类用作锁定对象。

In both cases, synchronized methods prevent other calls to similarly (instance or static) synchronized methods from being made simultaneously by different threads. 在这两种情况下,同步方法都可以防止其他线程同时对类似(实例或静态)同步方法进行其他调用。

Non synchronized code will not be affected. 非同步代码将不受影响。

That means that the method1 method, or any other method in that class declared as static synchronized , or any block of code synchronized using synchronized (StsticSyncTest.class) , will be mutually exclusive: two threads won't be able to concurrently enter two of these methods/code blocks. 这意味着method1方法或该类中任何其他声明为static synchronized ,或使用synchronized (StsticSyncTest.class)同步的任何代码块将是互斥的:两个线程将无法同时输入两个这些方法/代码块。

In short, it acts exactly as any other synchronized block, but the object used as a lock here is the unique instance, created by the classloader, of Class<StsticSyncTest> : StsticSyncTest.class. 简而言之,它的作用与任何其他同步块完全相同,但是这里用作锁的对象是Class<StsticSyncTest> :StsticSyncTest.class的由类加载器创建的唯一实例。

Synchonizing means that only one thread can run this method at the same time. 同步意味着只有一个线程可以同时运行此方法。 All the other threads attempting to run this method will block until the first one completes (which, in your case, will never happen, since you have an endless loop there). 尝试运行此方法的所有其他线程将阻塞,直到第一个线程完成为止(对于您而言,这将永远不会发生,因为在那里存在无限循环)。 It has nothing to do with object creation. 它与对象创建无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM