This is the general form of the synchronized statement:
synchronized(objRef) { // statements to be synchronized }
Here, objRef
is a reference to the object being synchronized.
A synchronized block ensures that on two threads will run the same code.
// This program uses a synchronized block. class Callme {/*w ww . java2s . c o m*/ void call(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; public Caller(Callme targ, String s) { target = targ; msg = s; } // synchronize calls to call() public void run() { synchronized(target) { // synchronized block target.call(msg); } } } public class Main { public static void main(String args[]) { Callme target = new Callme(); Thread t1 = new Thread(new Caller(target, "Hello")); t1.start(); Thread t2 = new Thread(new Caller(target, "Synchronized")); t2.start(); Thread t3 = new Thread(new Caller(target, "World")); t3.start(); // wait for threads to end try { t1.join(); t2.join(); t3.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } }