Monday, February 1, 2016

[Java] Synchronized

Synchronized

1 synchronized + aMethod(){} : is for the method of an instance

2 synchronized  static aStaticMethod(){} for a class

3 synchronized (this) {/*block*/}

4 synchronized in inherit : you should use the key word to inherit, the default is not synchronized:

base class : sychronized f(){}
sub class : f(){} is not synchronized
you should do sub class synchronized f(){}

5 An example of dead lock

class DeadLock{
     public final Object lock1 = new Object();
     public final Object lock2 = new Object();

     public void f1() {
          synchronized(lock1){
                 synchronized(lock2){....... }
          }
     }
     public void f2() {
          synchronized(lock2){
                 synchronized(lock1){....... }
          }
     }
}

No comments:

Post a Comment