Thread Synchronization
When two or
more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time.
The process
by which this synchronization is achieved is called thread
synchronization.
The
synchronized keyword in Java creates a block of code referred to as a critical
section. Every Java object with a critical section of code gets a lock
associated with the object. To enter a critical section, a thread needs to
obtain the corresponding object's lock.
This is the
general form of the synchronized statement:
synchronized(object)
{
// statements to be synchronized
}
|
Here,
object is a reference to the object being synchronized. A synchronized block
ensures that a call to a method that is a member of object occurs only after
the current thread has successfully entered object's monitor.
Here is an
example, using a synchronized block within the run( ) method:
//
File Name : Callme.java
//
This program uses a synchronized block.
class
Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
//
File Name : Caller.java
class
Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized
block
target.call(msg);
}
}
}
//
File Name : Synch.java
class
Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target,
"Hello");
Caller ob2 = new Caller(target,
"Synchronized");
Caller ob3 = new Caller(target,
"World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
|
This would
produce following result:
[Hello]
[World]
[Synchronized]
|
No comments:
Post a Comment