Вопрос

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

Это было полезно?

Решение

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.

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.

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 с атрибуция
Не связан с StackOverflow
scroll top