Home Tutorial Java Corejava Using a synchronized block


Share on Google+Share on Google+
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.


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


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

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

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

  public void run() {
    synchronized (target) { 

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 {
    catch (InterruptedException e) {
      System.out.println("Interrupted "+e);


Download this code


Related Tags for Using a synchronized block:

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: June 25, 2010

Recommend the tutorial

Advertisements Advertisements