Synchronized block example
Instead of synchronizing the entire method we can synchronize a small piece of code using block.
Example
public class Sample implements Runnable { public void print() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } synchronized(this) { for (int i = 6; i < 10; i++) { System.out .println(Thread.currentThread().getName() + " synchronized: " + i); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void run() { // TODO Auto-generated method stub print(); } }
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Sample s1 = new Sample(); Sample s2 = new Sample(); Thread t1 = new Thread(s1); Thread t2 = new Thread(s1); Thread t3 = new Thread(s2); t1.setName("t1"); t2.setName("t2"); t3.setName("t3"); t1.start(); t2.start(); t3.start(); } }
Output:
t2: 0 t3: 0 t1: 0 t1: 1 t3: 1 t2: 1 t3: 2 t2: 2 t1: 2 t3: 3 t2: 3 t1: 3 t2: 4 t3: 4 t1: 4 t2 synchronized: 6 t3 synchronized: 6 t2 synchronized: 7 t3 synchronized: 7 t2 synchronized: 8 t3 synchronized: 8 t3 synchronized: 9 t2 synchronized: 9 t1 synchronized: 6 t1 synchronized: 7 t1 synchronized: 8 t1 synchronized: 9