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
Advertisement
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

Advertisement

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
 

 

 

DMCA.com