Thread Part V
Synchronize,
Monitor/Lock for Thread
All
threads in java each other share memory space, it means all threads
share resource each other too. When the threads access the resource,
sometime we need to convince that only one thread access the source
one at time. For handling this situation we use synchronize. The
concept is java provide structure to synchronize all threads activity
is called monitor or lock it
mean if one thread access the resource the thread must have monitor
first for accessing resource, and the monitor can have just for one
thread only, if the thread got monitor it mean the thread is in
monitor and monitor is locked. It means all other threads try to get
monitor must wait until the thread in monitor must release the
monitor first.
If
the object is accessed just only for one thread, the method for
accessing the object must put keyword in method that thread is
accessed synchronized .
OK
let’s try how synchronize and monitor work in java first we create
the class or object to be accessed by thread.
public
class
Test {
public
synchronized
void
test(String s){
System.out.println("
[ "+s);
try
{
Thread.sleep(1000);
}
catch
(Exception e) {
e.printStackTrace();
}
System.out.println("]");
}
}
public
class
MythreadBlock implements
Runnable{
private
Test test;
private
Thread thread;
private
String message;
MythreadBlock(Test
test, String message){
thread
= new
Thread(this);
this.test
= test;
this.message
= message;
thread.start();
}
@Override
public
void
run() {
test.test(message);
}
}
and let’s try how synchronize work by using code bellow
public
class
MythreadBlockDemo {
public
static
void
main(String[] args) {
Test
test = new
Test();
MythreadBlock
t1 =
new
MythreadBlock(test, "this");
MythreadBlock
t2 =
new
MythreadBlock(test, "demonstarion");
MythreadBlock
t3 =
new
MythreadBlock(test, "synchorize");
}
}
if we run the code above the result will show as bellow,
[
this]
[
synchorize]
[
demonstarion]
[this[demonstarion[syncrhonize]]
]
Sometime we need to synchronize not in our resources that we want to access, the resources just synchronize if was called only thread. For this condition we can put synchronize in our thread.
We will use the same resource as above but we remove synchronize word from the method test().
And now create thread for accessing the resources with monitor or synchronize way.
public
class
MythreadBlock implements
Runnable{
private
Test test;
private
Thread thread;
private
String message;
MythreadBlock(Test
test, String message){
thread
= new
Thread(this);
this.test
= test;
this.message
= message;
thread.start();
}
@Override
public
void
run() {
//
this we implement the synchronize
synchronized
(message) {
test.test(message);
}
}
}
No comments:
Post a Comment