Synchronization multithreading in Java

The mechanism by which access to a single resource by multiple thread is controlled is called synchronization.Method level synchronization is the way to manage your thread of execution.

 

class Share extends Thread

{

static String msg[]={"This", "is", "a", "synchronized", "variable"};

Share(String threadname)

{

super(threadname);

}

public void run()

{

displayy(getName());//calling function

}

public synchronized void displayy(String threadNN)//method level synchronization

{

for(int i=0;i<=4;i++)

System.out.println(threadNN+msg[i]);

try

{

this.sleep(1000);

}

catch(Exception e)

{

}

}

}

public class syn1

{

public static void main(String[] argss)

{

Share t1=new Share("Thread One: ");

t1.start();

Share t2=new Share("Thread Two: ");

t2.start();

}

}

 synchronization in java

Explanation…

In above example we use Method level synchronization(keyword) prevents two threads from executing method on an object at the same time(one time).When a thread invokes a synchronized method on as object, the thread first acquires a lock on that object,execute the body of the method and then release the lock.Once a lock has been obtained by one thread, no other thread can acquired the lock on the object until the thread releases(wait until the lock has been released).