• August 29, 2014
  • Core Java
  • Comments Off on Static synchronization in java

Static synchronization in java

Static synchronization is achieved by static synchronized methods. Static synchronized method locked on class and non-static synchronized method locked on current object i.e. static and non-static synchronized methods can run at same time. It can produce inconsistency problem.

If static synchronized method is called a class level lock is acquired and then if an object is tries to access non-static synchronized method at the same time it will not be accessible because class level lock is already acquired.

Example:

MultiThreadExample.java

/**
 * This program is used to show the multithreading 
 * example with synchronization using static synchronized method.
 * @author javawithease
 */
class PrintTable{    
    public synchronized static void printTable(int n){
	   System.out.println("Table of " + n);
       for(int i=1;i<=10;i++){
           System.out.println(n*i);  
           try{  
        	 Thread.sleep(500);  
           }catch(Exception e){
        	 System.out.println(e);
           }  
        }         
    }  
}  
 
class MyThread1 extends Thread{    
    public void run(){ 
    	PrintTable.printTable(2);  
    }        
}  
 
class MyThread2 extends Thread{   
	public void run(){  
		PrintTable.printTable(5);  
	}  
}  
 
public class MultiThreadExample{  
    public static void main(String args[]){
 
    	//creating threads.
	    MyThread1 t1=new MyThread1();  
	    MyThread2 t2=new MyThread2();  
 
	    //start threads.
	    t1.start();  
	    t2.start();  
    }  
}

Output:

Table of 2
2
4
6
8
10
12
14
16
18
20
Table of 5
5
10
15
20
25
30
35
40
45
50

Download this example.

Difference between static and non-static synchronized method.

    Non-Static synchronized method       Static synchronized method
  1. 1. Lock is on object.
  2. 2. Commonly used.
  3. 3. Static keyword is not used.
  1. 1. Lock is on class.
  2. 2. Not commonly used.
  3. 3. Used with static keyword.

 
Next Topic: Synchronized block in java with example.
Previous Topic: Synchronized method in java with example.

Related Topics:

Multithreading in java.
Thread life cycle in java.
Way of creating thread in java.
Commonly used methods of Thread class.
Thread scheduling in java with example.
Thread priority in java with example.
Naming a thread in java with example.
Joining a thread in java with example.
Daemon thread in java with example.
Can we start a thread twice?
Can we call run method directly?
Difference between Thread.yield() and Thread.sleep() methods.
Deadlock in java with example.
Starvation in java with example.
Inter-thread communication in java with example.
Synchronization in java with example.
Synchronized method in java with example.
Static synchronization in java with example.
Synchronized block in java with example.

 


Comments are closed.