CodesJava

Easy learning with example program codes

Synchronized block in java


Synchronized block:

Synchronized block is used to synchronize a critical block of code instead of whole method.

Note: Synchronized block is preferred over synchronized method because in case synchronized block only critical block of code is locked not whole method, hence performance will be better in this case.
Throw NullPointerException if object passed in synchronized block is null.

Example:

MultiThreadExample.java

/**
 * This program is used to show the multithreading 
 * example with synchronization using synchronized block.
 * @author codesjava
 */
class PrintTable{    
    public void printTable(int n){
       synchronized(this){
    	   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{  
    PrintTable pt;  
    MyThread1(PrintTable pt){  
    	this.pt=pt;  
    }  
    public void run(){ 
    	pt.printTable(2);  
    }        
}  
 
class MyThread2 extends Thread{  
	PrintTable pt;  
	MyThread2(PrintTable pt){  
		this.pt=pt;  
	}  
	public void run(){  
		pt.printTable(5);  
	}  
}  
 
public class MultiThreadExample{  
    public static void main(String args[]){
    	//creating PrintTable object.
    	PrintTable obj = new PrintTable();  
 
    	//creating threads.
	    MyThread1 t1=new MyThread1(obj);  
	    MyThread2 t2=new MyThread2(obj);  
 
	    //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 synchronized method and synchronized block.

            Synchronized method             Synchronized block
  1. Lock is acquired on whole method.
  2. Less preferred.
  3. Performance will be less as compared to synchronized block.
  1. Lock is acquired on critical block of code only.
  2. preferred.
  3. Performance will be better as compared to synchronized method.

 
Next Topic: Input output (I/O) in java.
Previous Topic: Static synchronization in java with example.

Related Topics:

Posted in Java   

Core Java Tutorial

Programming language overview.
Overview of Java.
Java features
JVM architecture details.
JVM, JRE and JDK.
Java Coding Guidelines.
Some important definitions.
Variable and data types.
Hello world java program.
Core java examples programs.
Important Java Programs.
How to set permanent path in java?
OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.
Method overloading in java.
Method overriding in java.
Dynamic method dispatch.
Runtime polymorphism.
Association in java.
Inheritance in java.
Aggregation in java.
Command line arguments in java.
Command line argument program in eclipse.
Read input from command line using Scanner.
Java array programs
Java star pattern programs
Java number pattern programs
final in java.
Abstract class in java.
Interface in java.
Custom marker Interface in java.
Constructor in java.
Package in java.
Access modifier in java.
Static import in java.
Package class in java.
this in java.
Instance initialize block.
Anonymous block.
super in java.
Static in java.
final in java.
Java cloning deep and shallow
Shallow vs Clone copy
String handling in java.
String handling programs.
StringBuffer in java.
StringBuilder in java.
Exception Handling Tutorial.
Multithreading Tutoial.
Java input output stream tutorial.
Collections framework in java tutorial.
Collections framework programs.
Java Random class
Java annotations.
Java design principles.
Java 7 features
Java 8 features
Java networking tutorial
Java Reflection tutorial


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap