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”]
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
2 Responses
Thanks for this example. This is very useful to understand Synchronization
This site is really cool. I have bookmarked it.