Java Synchronized Block
In the previous chapter, we have studied the Java synchronizing methods. In this tutorial we are looking into the way by which we can synchronize the particular part of the method.
Java Synchronized Block :
Consider the following syntax of the synchronized block -
synchronized (object reference expression) { //code lines }
Suppose we need to synchronize only 4-5 lines of code out of 100 lines then we can put 4-5 lines in the synchronize block.
void displayTable(int n) throws InterruptedException { synchronized (this) { for (int i = 1; i <= 5; i++) { System.out.println(n * i); Thread.sleep(400); } } }
In the above method we have made some part of the java method synchronized.
Example #1 : Synchronized Block
class TableClass { void displayTable(int n) { synchronized (this) { for (int i = 1; i <= 5; i++) { System.out.println(n * i); try { Thread.sleep(400); } catch (Exception e) { System.out.println(e); } } } } } class MyThread1 extends Thread { TableClass c1; MyThread1(TableClass tObj) { this.c1 = tObj; } public void run() { c1.displayTable(5); } } class MyThread2 extends Thread { TableClass c2; MyThread2(TableClass tObj) { this.c2 = tObj; } public void run() { c2.displayTable(100); } } class SynchronizeExample { public static void main(String args[]) { TableClass obj = new TableClass(); MyThread1 t1 = new MyThread1(obj); MyThread2 t2 = new MyThread2(obj); t1.start(); t2.start(); } }
Output :
5 10 15 20 25 100 200 300 400 500