Synchronized block:
Synchronized block is mainly used when there is a sharing of resources and it is used to lock an object for any shared resource so that at a particular time only one object can use that resource. By using synchronized block only one thread can use that resource at a particular time. It eliminates thread interference and consistency problem.
Example:
    class Table{  
      
     void printTable(int n){  
       synchronized(this){//synchronized block  
         for(int i=1;i<=5;i++){  
          System.out.println(n*i);  
          try{  
           Thread.sleep(400);  
          }catch(Exception e){System.out.println(e);}  
         }  
       }  
     }//end of the method  
    }  
      
    class Thread1 extends Thread{  
    Table t;  
    Thread1(Table t){  
    this.t=t;  
    }  
    public void run(){  
    t.printTable(5);  
    }  
      
    }  
    class Thread2 extends Thread{  
    Table t;  
    Thread2(Table t){  
    this.t=t;  
    }  
    public void run(){  
    t.printTable(100);  
    }  
    }  
      
    public class SynchronizedBlock1{  
    public static void main(String args[]){  
    Table obj = new Table();//only one object  
    Thread1 t1=new Thread1(obj);  
    Thread2 t2=new Thread2(obj);  
    t1.start();  
    t2.start();  
    }  
    }  
Output:
       5
       10
       15
       20
       25
       100
       200
       300
       400
       500
Synchronized block can  throw  java.lang.NullPointerException if expression provided to block as parameter evaluates to null.
                       
                    
0 Comment(s)