Hi friends, here I have attached Synchronization in Java Example Program. to understand synchronization and synchronized keyword usage in java programming language.

Bank.java

package com.javatraineronline.example;
public class Bank implements Runnable {
private int balance = 100;
@Override
public synchronized void run() {
// printing the thread name
System.out.println(Thread.currentThread().getName()+" came here!!!");
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" doing transaction!!!");
if(balance > 0) {
balance = balance - 10;
} else {
System.out.println("Insufficient balance ...");
}
try {
// Delaying the transaction for 1 second.
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}	
}

ATM.java

package com.javatraineronline.example;
public class ATM {
public static void main(String[] args) {
Bank boa = new Bank();
Thread tom = new Thread(boa);
tom.setName("Tom");
Thread jerry = new Thread(boa);
jerry.setName("Jerry");
// Starting the both thread
tom.start();
jerry.start();
}
}

Output

[su_box title=”Output for ATM.java”]Tom came here!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Tom doing transaction!!!
Jerry came here!!!
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
Jerry doing transaction!!!
Insufficient balance …
[/su_box]

Example Video

[su_youtube url=”https://www.youtube.com/watch?v=pxqRZvjRNoc&feature=youtu.be”]

Tags:

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *