Friday, September 13, 2013

Synchronization : Lesson 02


Synchronization : Lesson 02

Another example which show the synchronization behavior.

public class Print {

     synchronized void printMultiplicationNumbers(int n){

        for(int i = 1; i<5; i++){
           System.out.println(i*n);
           try{
              Thread.sleep(500);
           }catch (Exception e) {
              // TODO: handle exception
           }
        }
     }
}

public class TestExample {

   /**
   * @param args
   */
   public static void main(String[] args) {

      TestExample example = new TestExample();
      example.execute();
   }

   private void execute(){

      final Print p = new Print(); //only one object

      Thread thread01 = new Thread(){ 

         public void run(){
            p.printMultiplicationNumbers(5);
         }
      };

      Thread thread02 = new Thread(){

         public void run(){
            p.printMultiplicationNumbers(500);
         }
      };

      thread01.start();
      thread02.start();
   }
}

Output -

5
10
15
20
500
1000
1500
2000