All for Joomla All for Webmasters

Synchronized block in java

Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.

Points to remember for Synchronized block

  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.

Syntax to use synchronized block

  1. synchronized (object reference expression) {
  2.   //code block 
  3. }

Example of synchronized block

Let’s see the simple example of synchronized block.

Program of synchronized block

  1. class Table{
  2.  void printTable(int n){
  3.    synchronized(this){//synchronized block
  4.      for(int i=1;i<=5;i++){
  5.       System.out.println(n*i);
  6.       try{
  7.        Thread.sleep(400);
  8.       }catch(Exception e){System.out.println(e);}
  9.      }
  10.    }
  11.  }//end of the method
  12. }
  13. class MyThread1 extends Thread{
  14. Table t;
  15. MyThread1(Table t){
  16. this.t=t;
  17. }
  18. public void run(){
  19. t.printTable(5);
  20. }
  21. }
  22. class MyThread2 extends Thread{
  23. Table t;
  24. MyThread2(Table t){
  25. this.t=t;
  26. }
  27. public void run(){
  28. t.printTable(100);
  29. }
  30. }
  31. public class TestSynchronizedBlock1{
  32. public static void main(String args[]){
  33. Table obj = new Table();//only one object
  34. MyThread1 t1=new MyThread1(obj);
  35. MyThread2 t2=new MyThread2(obj);
  36. t1.start();
  37. t2.start();
  38. }
  39. }
Output:5
       10
       15
       20
       25
       100
       200
       300
       400
       500
       

Same Example of synchronized block by using annonymous class:

//Program of synchronized block by using annonymous class

  1. class Table{
  2. void printTable(int n){
  3.    synchronized(this){//synchronized block
  4.      for(int i=1;i<=5;i++){
  5.       System.out.println(n*i);
  6.       try{
  7.        Thread.sleep(400);
  8.       }catch(Exception e){System.out.println(e);}
  9.      }
  10.    }
  11. }//end of the method
  12. }
  13. public class TestSynchronizedBlock2{
  14. public static void main(String args[]){
  15. final Table obj = new Table();//only one object
  16. Thread t1=new Thread(){
  17. public void run(){
  18. obj.printTable(5);
  19. }
  20. };
  21. Thread t2=new Thread(){
  22. public void run(){
  23. obj.printTable(100);
  24. }
  25. };
  26. t1.start();
  27. t2.start();
  28. }
  29. }
Output:5
       10
       15
       20
       25
       100
       200
       300
       400
       500
PinIt
submit to reddit

Leave a Reply

Top