Synchronized provides lock which ensures mutually exclusive access to the shared resources.
The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. The more complex of the two, synchronized statements, are described in the next section. This section is about synchronized methods.
Following examples explains how synchronization is achieved using Synchronized using method
// Output.java
package com.learn;
class Output{
int currentSavingBalance=5000;
public synchronized void transcation(int amount){
currentSavingBalance= currentSavingBalance+amount;
System.out.println("Transcation completed");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Output output = new Output();
Withdraw withdraw = new Withdraw(output);
Deposit deposit = new Deposit(output);
Deposit deposit1 = new Deposit(output);
System.out.println(withdraw.getPriority());
System.out.println(deposit.getPriority());
withdraw.start();
deposit.start();
}
}
////////////////////////////////////////////////////
package com.learn;
public class Withdraw extends Thread {
Output output;
public Withdraw(Output output) {
this.output = output;
}
public void run(){
System.out.println("Withdraw strated current balace is :"+output.currentSavingBalance);
output.transcation(-3000);
System.out.println("Withdraw Done current balance is:"+output.currentSavingBalance);
}
}
/////////////////////////////////////////////
package com.learn;
public class Deposit extends Thread {
Output output;
public Deposit(Output output) {
this.output = output;
}
public void run(){
System.out.println("Deposit started current balance is :"+output.currentSavingBalance);
output.transcation(5000);
System.out.println("Deposit done current balance is :"+output.currentSavingBalance);
}
}
////////////////////////OUTPUT when we run Output.java as java application//////////////////////////
5
5
Withdraw strated current balace is :5000
Transcation completed
Deposit started current balance is :2000
Withdraw Done current balance is:2000
Transcation completed
Deposit done current balance is :7000
No comments:
Post a Comment