Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Thread Thread Synchronization in Java

Related Tutorials


 
 

Share on Google+Share on Google+

Thread Synchronization in Java

Advertisement
In this section, you will learn Thread Synchronization in Java

Thread Synchronization in Java

Sometimes, when two or more threads need shared resource, they need a proper mechanism to ensure that the resource will be used by only one thread at a time.

The mechanism we use to achieve this is known as thread synchronization.

The thread synchronization is achieved through the synchronized keyword. The statements which need to be synchronized should put into the synchronized block It is also known as critical section. The synchronized block is defined as follows :

synchronized(object) {
   // statements to be synchronized
}

Object in Java which have synchronization block(critical section) gets a lock related with the object. To get access to the critical section or synchronization block you need the associated object's lock.

EXAMPLE

Given below the example using a synchronized block having thread synchronization :

class Print {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}

class PrintCaller implements Runnable {
String msg;
Print target;
Thread t;

public PrintCaller(Print 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);
}
}
}

public class TreadSynchroniztion {
public static void main(String args[]) {
Print target = new Print();
PrintCaller ob1 = new PrintCaller(target, "Hello");
PrintCaller ob2 = new PrintCaller(target, "Synchronized");
PrintCaller ob3 = new PrintCaller(target, "World");

// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
}

OUTPUT :

[Hello]

[World]

[Synchronized]


Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 22, 2011

Related Tutorials

Discuss: Thread Synchronization in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com