Wednesday, 27 June 2012

{Synchronization} Object and Class level lock

package com.test;

public class TestThreadLock {

   public static void main(String... strings) {
      TestThread t = new TestThread();
      Thread t1 = new Thread(t);
      Thread t2 = new Thread(t);
      t1.start();
      t2.start();
   }

}

class TestThread implements Runnable {

   @Override
   public void run() {
      System.out.println("Hello");
      fun1();
      fun2();
      fun3();
      fun4();
      fun5();
      fun6();
   }

   public void fun1() {
      System.out.println("fun1");
   }

   public synchronized void fun2() {
      System.out.println("fun2");
   }

   public void fun3() {
      synchronized (this) {
         System.out.println("fun3");
      }
   }

   public static void fun4() {
      System.out.println("fun4");
   }

   public static synchronized void fun5() {
      System.out.println("fun5");
   }

   public void fun6() {
      synchronized (TestThread.class) {
         System.out.println("fun6");
      }
   }

}