Synchronization
: Lesson 01
Synchronization
is the capability of control the access of multiple threads to any
shared resource.
(
Only one thread access the shared resource at a time )
Why
synchronization ?
- To prevent thread interference
- To prevent consistency problem
Synchronization
types :-
- Process synchronization
- Thread synchronization
Thread
synchronization
2
types:
*
Inter thread communication
*
mutual exclusive
Mutual
Exclusive
Mutual
Exclusive helps keep threads form interfering with one another while
sharing data.
This
can be done in three ways.
- by synchronized method
- by synchronized block
- by static synchronization
Example
with no Synchronization -
1.
Print.java
public
class Print
{
void
printMultiplicationNumbers(int
n){
for(int
i = 1; i<5; i++){
System.out.println(i*n);
try{
Thread.sleep(500);
}catch
(Exception e) {
//
TODO:
handle exception
}
}
}
}
2.
Thread01.java
public
class
Thread01 extends
Thread {
Print
print;
Thread01(Print
p){
this.print
= p;
}
public
void
run(){
print.printMultiplicationNumbers(5);
}
}
3.
Thread02.java
public
class
Thread02 extends
Thread {
Print
print;
Thread02(Print
p){
this.print
= p;
}
public
void
run(){
print.printMultiplicationNumbers(100);
}
}
4.
TestExecute.java - class
to run above thread simultaneously to access the Print resource java
class.
public
class
TestExecute {
/**
* @param
args
*/
public
static
void
main(String[] args)
Print
p = new
Print();
Thread01
thread01 = new
Thread01(p);
Thread02
thread02 = new
Thread02(p);
thread01.start();
thread02.start();
}
}
Output
( no-synchronize example) :
5
100
10
200
15
300
20
400
Use
of Synchronized method
Declared
any method as synchronized, it is known as synchronized method.
Synchronized
method used to lock an object for any shared resource.
When
a Thread invokes a synchronized method, the lock will be granted and
it will returns once the method got return.
Example
with synchronized method
1.
Print.java – with
synchronized method
public
class
Print {
synchronized
void
printMultiplicationNumbers(int
n){
for(int
i = 1; i<5; i++){
System.out.println(i*n);
try{
Thread.sleep(500);
}catch
(Exception e) {
//
TODO:
handle exception
}
}
}
}
Output
( synchronized example) :
5
10
15
20
100
200
300
400