# Synchronizing multiple threads in JAVA

In the previous tutorial, we learned about Thread states in Java. In this tutorial, we will learn How to synchronize threads in Java.

76

If we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource.

This problem doesn’t seem to be a big one, but it may cause corruption in data values and problem if we are dealing with real-world entities.

For example, we are making a program for bank management in which we are withdrawing and depositing some amount with the help of multiple threads. For example, we have an initial amount of 500 in our bank, and we are depositing 2000 and withdrawing 2000 each time. If the two threads run in a normal way without synchronization, then it may be possible that the second thread runs 2 times and the first thread is not run. This will lead to problems because the balance will go negative. Whereas, if we synchronize these threads such that the balance is withdrawn only once after it is deposited, this problem is solved and will cause no error.

So, we need to synchronize the action of multiple threads and make sure that only one thread can access a given resource at a time. And the threads don’t run in a mismatched manner.

Conventionally, a thread needs constant access to a resource. So, for this, we need to synchronize the threads. We will try to understand this with the help of the example given below –

### Without Synchronization  –

class Yuvayana{

void printYuvayana(int n){

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

}catch(Exception e){System.out.println(e);}

}           }  }

Yuvayana t;

this.t=t;

}

public void run(){

t.printYuvayana(5);

}

}

Yuvayana t;

this.t=t;

}

public void run(){

t.printYuvayana(100);

}  }

class TestSynchronization1{

public static void main(String args[]){

Yuvayana obj = new Yuvayana();

t1.start();

t2.start();

}

} 

Output –

       5

100

10

200

15

300

20

400

25

500

### Synchronized Method –

class Yuvayana{

synchronized void printYuvayana(int n){

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

}catch(Exception e){System.out.println(e);}}

}

Yuvayana t;

this.t=t;

}

public void run(){

t.printYuvayana(5);

}

}

Yuvayana t;

this.t=t;

}

public void run(){

t.printYuvayana(100);

}

}

public class TestSynchronization2{

public static void main(String args[]){

Yuvayana obj = new Yuvayana();

t1.start();

t2.start();

}

}

Output –

 5    10    15    20     25    100    200    300    400    500

Attempt Free Java MCQ Test

Previous articleKeys in DBMS
Next articleCategories of Database Languages
I am Harshit Brijwasi. I am an engineer and a Technical Content writer. I am here to share my knowledge about technical topics and help researchers with them.

This site uses Akismet to reduce spam. Learn how your comment data is processed.