Java Synchronized Method
Chapter:
Thread
Last Updated:
10-10-2017 15:56:11 UTC
Program:
/* ............... START ............... */
//example of java synchronized method
class Table {
synchronized void printTable(int n) {// synchronized method
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 {
Table t;
MyThread1(Table t) {
this.t = t;
}
public void run() {
t.printTable(100);
}
}
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
public void run() {
t.printTable(1000);
}
}
public class JavaSynchronizedMethod {
public static void main(String args[]) {
Table obj = new Table();// only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
/* ............... END ............... */
Output
100
200
300
400
500
1000
2000
3000
4000
5000
Notes:
-
Synchronization is a mechanism in java by which only one thread can access the resource at a given point of time.
- If a method is declared as synchronized, it is act as synchronized method.
- Synchronized method is used to lock an object for any shared resource.
- When a thread invokes a synchronized method, it will automatically acquires the lock for that object and releases it when the thread completes its task.
- In the above program we can see that even if we are executing two thread t1 and t2 at the same time, synchronized method printTable of t1 executes completely and comes to the next thread t2.
- If the function printTable is not synchronize it will randomly print the values from thread t1 and t2.
Tags
Synchronized Method, Java, Thread