Synchronization
: Lesson 03 – Synchronized Block
Synchronization
blocked can be used to perform synchronization on any specific
resource of the method.
Syntax
:
synchronized(object
reference
expression){
//code
block
}
1.
ArithmeticOperations.java
public
class ArithmeticOperations
{
public
void
doArithmeticOperations(int
x, int
y){
System.out.println("Thread
Name doArithmeticOperations() : " +
Thread.currentThread().getName());
int
sum = printSummation(x,y);
synchronized
(this)
{
printMultiplicationNumbers(sum);
}
}
private int
printSummation(int
x, int
y){
System.out.println("Thread
Name printSummation() : " +
Thread.currentThread().getName());
System.out.println("Number
01 : " + x + "
Number 02 : " + y + "
Summation is : " + (x + y));
return
x+y;
}
private
void
printMultiplicationNumbers(int
n){
System.out.println("Thread
Name printMultiplicationNumbers() : "
+ Thread.currentThread().getName());
for(int
i = 1; i<5; i++){
System.out.println("Multiplication
" + i*n);
try{
Thread.sleep(500);
}catch
(Exception e) {
//
TODO:
handle exception
}
}
}
}
2.
TestSynchronizedBlock.java
public
class TestSynchronizedBlock {
public
static
void
main(String[] args) {
TestSynchronizedBlock
example = new
TestSynchronizedBlock();
example.execute();
}
private
void
execute(){
final
ArithmeticOperations operations = new
ArithmeticOperations(); //only one
object
Thread
thread01 = new
Thread(){
public
void
run(){
operations.doArithmeticOperations(5,
10);
}
};
Thread
thread02 = new
Thread(){
public
void
run(){
operations.doArithmeticOperations(15,
20);
}
};
thread01.start();
thread02.start();
}
}
Output
-
Thread
Name doArithmeticOperations() : Thread-0
Thread
Name printSummation() : Thread-0
Number
01 : 5 Number 02 : 10 Summation is : 15
Thread
Name printMultiplicationNumbers() : Thread-0
Multiplication
15
Thread
Name doArithmeticOperations() : Thread-1
Thread
Name printSummation() : Thread-1
Number
01 : 15 Number 02 : 20 Summation is : 35
Multiplication
30
Multiplication
45
Multiplication
60
Thread
Name printMultiplicationNumbers() : Thread-1
Multiplication
35
Multiplication
70
Multiplication
105
Multiplication
140