You know threads allow multiple activities to proceed concurrently. While execution multiple threads may share common resources. Thus multiple threads compete for the common resources, called race condition. However, there are critical situations, where it is desirable that only one thread at a time has an access to a shared resource to avoid the race condition. The process, by which this is achieved is called synchronization.
Synchronization works with locks. Every object in Java has a built-in lock, that only comes into play when the object has synchronized method or synchronized block. As the synchronized method or block executes, a lock is imposed on instance, consisting of the synchronized code. We can also use term monitor for the locked object. There is only one lock per object, if one thread picked the lock, no other thread can pick it until the first thread releases the lock. In other words, no other thread can enter the synchronized code. Releasing the lock means, the thread which was entered in synchronized code (method or block) exits from it.
Synchronized methods are useful when methods can manipulate the state of an object in ways that can corrupt the state, if executed concurrently.
For Example:
// SynchronizedMethod.java class Resource { synchronized void printTable(int tbl) //synchronized method { for(int i=1;i<=5;i++) { int value=tbl*i; System.out.println(tbl+”*”+i+”=”+value); try{ Thread.sleep(100);} catch(Exception ex){ex.printStackTrace();} } } } class User implements Runnable { Resource res; Thread th; int tbl; User(Resource res, int tbl) { this.res=res; this.tbl=tbl; th=new Thread(this); th.start(); } public void run() { res.printTable(tbl); } } public class SynchronizedMethod { public static void main(String[] args) { Resource res=new Resource(); //creation of object to be shared User thrd1=new User(res, 5); // object shared with thrd1 User thrd2=new User(res, 10); //object shared with thrd2 } }
Output 10*2=20 10*1=10 10*3=30 10*4=40 10*5=50 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25