synchronized
methods acquires a lock on object where as static synchronized
methods acquire a lock on class. Only one object of particular class
can enter into the static synchronized method at a time. One class
has one class lock with it.
Syntax
static
synchronized returnType methodName(parameters){
}
Example:
without synchronization for static method
class ClassLockEx implements Runnable{ static void printMethod(){ for(int i=0; i < 5; i++){ try{ Thread.currentThread().sleep(1000); } catch(Exception e){ System.out.println(e); } System.out.println(Thread.currentThread().getName() + " " + i); } } public void run(){ printMethod(); } public static void main(String args[])throws Exception{ ClassLockEx obj1 = new ClassLockEx(); ClassLockEx obj2 = new ClassLockEx(); Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); t1.start(); t2.start(); } }
Sample
Output
Thread-0 0 Thread-1 0 Thread-0 1 Thread-1 1 Thread-0 2 Thread-1 2 Thread-0 3 Thread-1 3 Thread-0 4 Thread-1 4
As
you see run method calling the“ printMethod”, which is static, so
both the objects obj1, obj2 has access to the static method. So both
are running parallelly. By using static synchronized method, Only one
object can run the method at a time.
Use
of static synchronized method
class ClassLockEx implements Runnable{ static synchronized void printMethod(){ for(int i=0; i < 5; i++){ try{ Thread.currentThread().sleep(1000); } catch(Exception e){ System.out.println(e); } System.out.println(Thread.currentThread().getName() + " " + i); } } public void run(){ printMethod(); } public static void main(String args[])throws Exception{ ClassLockEx obj1 = new ClassLockEx(); ClassLockEx obj2 = new ClassLockEx(); Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); t1.start(); t2.start(); } }
Output
Thread-0 0 Thread-0 1 Thread-0 2 Thread-0 3 Thread-0 4 Thread-1 0 Thread-1 1 Thread-1 2 Thread-1 3 Thread-1 4
With
the help of static synchronization, until one object finishes it's
execution with the static synchronized method, other objects must
wait to run the same or other static synchronization methods of the
same class.
No comments:
Post a Comment