• Register

In synchronization, 2 kinds of locks on threads:

1.    Object level lock : Each obj in java has a single lock. When we are using synchronized keyword, then solitary lock idea will arise in the picture. If a thread needs to run synchronized function on the given obj. Initially, it has to acquire lock of that object. After thread acquired the lock at that time it is permitted to perform any synchronized function on that object.

// Java program to illustrate 
// Object lock concept 
class Geek implements Runnable { 
    public void run() 
    { 
        Lock(); 
    } 
    public void Lock() 
    { 
        System.out.println(Thread.currentThread().getName()); 
        synchronized(this) 
        { 
            System.out.println("in block "
                + Thread.currentThread().getName()); 
            System.out.println("in block " +  
                Thread.currentThread().getName() + " end"); 
        } 
    } 
    public static void main(String[] args) 
    { 
        Geek g = new Geek(); 
        Thread t1 = new Thread(g); 
        Thread t2 = new Thread(g); 
        Geek g1 = new Geek(); 
        Thread t3 = new Thread(g1); 
        t1.setName("t1"); 
        t2.setName("t2"); 
        t3.setName("t3"); 
        t1.start(); 
        t2.start(); 
        t3.start(); 
    } 
} 

Output:

t1
in block t1
in block t1 end
t2
in block t2
in block t2 end
t3
in block t3
in block t3 end

1.    Class level lock : Each class in java has a matchless lock which is nothing but class level lock. If a thread needs to run a static synchronized function, then thread needs class level lock. Let us see  following program for improved perceiving :

// to show class level lock 
class kodlogs implements Runnable { 
    public void run() 
    { 
        Lock(); 
    } 
  
    public void Lock() 
    { 
        System.out.println(Thread.currentThread().getName1()); 
        synchronized(Kodlogs.class) 
        { 
            System.out.println("in block " 
                + Thread.currentThread().getName1()); 
            System.out.println("in block " 
                + Thread.currentThread().getName()1 + "the end"); 
        } 
    } 
  
    public static void main(String[] args) 
    { 
        Kodlogs kd = new Kodlogs(); 
        Thread t11 = new Thread(kd); 
        Thread t21 = new Thread(kd); 
        Kodlogs g21 = new Kodlogs(); 
        Thread t31 = new Thread(g21); 
        t1.setName("t11"); 
        t2.setName("t21"); 
        t3.setName("t31"); 
        t11.start(); 
        t21.start(); 
        t31.start(); 
    } 
} 

Output:

t11
in block t1
in block t11 end
t21
in block t2
in block t21 end
t3
in block t31
in block t31 end

 

2,760 points
7 4