Java - Thread Synchronization

Java - Thread Synchronization | Javamazon:

'via Blog this'

thread synchronization in java

Before We have discussed about :
Now will discuss small Demo on 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 is an example, using a synchronized block within the run( ) method:
// File Name :

// This program uses a synchronized block.
class SyncMe {
   void Meth(String msg) {
      System.out.print("[" + msg);
      try {
      } catch (InterruptedException e) {

// File Name :
class Synced implements Runnable {
   String msg;
   SyncMe target;
   Thread t;
   public Synced(SyncMe targ, String s) {
      target = targ;
      msg = s;
      t = new Thread(this);

   // synchronize here
   public void run() {
      synchronized(target) { // synchronized block
// File Name :
class Synch {
   public static void main(String args[]) {
      SyncMe target = new SyncMe();
      Synced obj1 = new Synced(target, "Hello");
      Synced obj2 = new Synced(target, "Synchronized");
      Synced obj3 = new Synced(target, "World");

      // wait for threads to end
      try {
      } catch(InterruptedException e) {
For Users familar with threads they can have a quick look on Multi Threading/Tasking Interview Questions


Post a Comment