Home Tutorial Java Corejava Using a synchronized block

 
 

Using a synchronized block
Posted on: June 25, 2010 at 12:00 AM
Every Class loaded and every Java object you create have an associated lock or monitor. When code are kept in a synchronized block makes the compiler append instruction to acquire the lock on the specified object before it executes the code and release it afterward.

Description:

This tutorial demonstrate how to implement synchronized block. In multithreading application a synchronized block is used to acquires the lock for an object.

Code:

class Called {
  void calling(String msg) {
    System.out.print("<" + msg);
    try {
      Thread.sleep(2000);
    catch (InterruptedException e) {
      System.out.println("Interrupted "+e);
    }
    System.out.print(">");
  }
}

class Caller implements Runnable {
  String msg;
  Called target;
  Thread t;

  public Caller(Called targ, String s) {
    target = targ;
    msg = s;
    t = new Thread(this);
    t.start();
  }

  public void run() {
    synchronized (target) { 
      target.calling(msg);
    }
  }
}

class SynchBlock {
  public static void main(String args[]) {
    Called target = new Called();
    Caller ob1 = new Caller(target, "First");
    Caller ob2 = new Caller(target, "Second");
    Caller ob3 = new Caller(target, "Third");

    try {
      ob1.t.join();
      ob2.t.join();
      ob3.t.join();
    catch (InterruptedException e) {
      System.out.println("Interrupted "+e);
    }
  }
}

Output:

Download this code

Related Tags for Using a synchronized block:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.