Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Method Synchronized

"Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods".

When a method is declared by the keyword synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

Let's see an example of synchronized method:

Example
class Demo
{
	synchronized void print(int n)    //synchronized method
	{                                                                             
		for(int i=1;i<=3;i++)
		{
			System.out.println(n*i);
			try
			{
				Thread.sleep(500);
			}
			catch(Exception e)
			{
				System.out.println(e);
			}
		}
	}
	class MyThread1 extends Thread
	{
		Demo d;
		MyThread1(Demo d)
		{
			this.d=d;
		}
		public void run()
		{
			d.print(5); 
		} 
	}
	class MyThread2 extends Thread
	{
		Demo d;
		MyThread2(Demo d)
		{
		this.d=d;
	}
	public void run()
	{
		d.print(10);
	}
}
public class SynchronizationExa1
{ 
	public static void main(String args[])
	{
		Demo obj = new Demo();                        
		MyThread1 obj1=new MyThread1(obj);
		MyThread2 obj2=new MyThread2(obj);  
		obj1.start(); 
		obj2.start(); 					  
	}
}
Output

5
10
15
10
20
30

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext