Java Synchronization
When two or more threads access the shared resource which makes ensure that only one thread can access the resource at a time. This process is called synchronization.
synchronized(object) { // statements to be synchronized }
Advantage of Synchronization
- It is used to prevent thread interference and consistency problem.
Synchronized Methods
When a thread is inside a synchronized method, all other threads that tries to call any other synchronized method on the same instance have to wait.
Synchronized method is used to lock an object for any shared resource.
Example:
Multithreading example without synchronization
class Calculate { void show(int n) { try { for(int i=1;i<=3;i++){ System.out.println(n*i); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("Interrupted"); } } } class Data implements Runnable { int n; Calculate ca; Thread t; public Data(Calculate c, int num) { ca = c; n = num; t = new Thread(this); t.start(); } public void run() { ca.show(n); } } public class WithoutSynchronization{ public static void main(String args[]) { Calculate ca = new Calculate(); Data d1= new Data(ca, 10); Data d2= new Data(ca, 100); try { d1.t.join(); d2.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } }
Example:
Multithreading example with synchronization
class Calculate { synchronized void show(int n) { try { for(int i=1;i<=3;i++){ System.out.println(n*i); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("Interrupted"); } } } class Data implements Runnable { int n; Calculate ca; Thread t; public Data(Calculate c, int num) { ca = c; n = num; t = new Thread(this); t.start(); } public void run() { ca.show(n); } } public class Synchronization{ public static void main(String args[]) { Calculate ca = new Calculate(); Data d1= new Data(ca, 10); Data d2= new Data(ca, 100); try { d1.t.join(); d2.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } }
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.