Synchronized method
- Eclipse: Oxygen
- Java: 1.8
Synchronized method
Synchronization is the ability to control the access of multiple threads to any shared resource.
Types of Synchronization
- Synchronized method
- Synchronized block
- Static synchronization
Let us discuss the synchronized method
The synchronized method is used to put a lock on a single object accessing the same entity (method) such as generate. The synchronized block is useless when there are different assigned objects since it uses MONITORS that are special types of blocks. Therefore, synchronized use will only guarantee a lock for a single object.
Without using the synchronization method we will get multiple outputs every time because both threads are getting execute simultaneously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Brakets{ public void generate(){ for(int i=1; i<=10; i++){ if(i<=5){ System.out.print("["); }else{ System.out.print("]"); } } System.out.println(); } } public class App { public static void main(String[] args) { Brakets braket = new Brakets(); new Thread(new Runnable() { @Override public void run() { for(int i=1; i<=5; i++){ braket.generate(); } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i=1; i<=5; i++){ braket.generate(); } } }).start(); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[[[[[]]]]][[[[[]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] ]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] |
In the following program, if you declare any method as synchronized, it is known as a synchronized method.
A synchronized method is used to prevent this public void generate() method to get executed on multiple threads simultaneously.
Making a method synchronized means that, this synchronized public void generate() method will not get executed multiple threads.
So, if more than one thread has a reference to the same method then only one thread can execute this method at a specific point of time. As a result, we will get consistency in output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Brakets{ synchronized public void generate(){ for(int i=1; i<=10; i++){ if(i<=5){ System.out.print("["); }else{ System.out.print("]"); } } System.out.println(); } } public class App { public static void main(String[] args) { Brakets braket = new Brakets(); new Thread(new Runnable() { @Override public void run() { for(int i=1; i<=5; i++){ braket.generate(); } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i=1; i<=5; i++){ braket.generate(); } } }).start(); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] [[[[[]]]]] |
Contributed by: Poonam Tomar