Java — Synchronization Method | Code Factory

Code Factory
2 min readMay 30, 2020

--

Index Page : Link

Donate : Link

WordPress Blog : Link

package com.example.thread;/**
* @author code.factory
*
*/
public class SynchronizedTest {
public static void main(String... args) {
Display d = new Display();
MyThread t1 = new MyThread(d, "Code");
MyThread t2 = new MyThread(d, "Factory");
t1.start();
t2.start();
}
}
class Display {
public synchronized void wish(String name) {
for(int i=0; i<5; i++) {
System.out.print("Display ");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(name);
}
}
}
class MyThread extends Thread {
Display d;
String name;
public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}
public void run() {
d.wish(name);
}
}

Output :

Display Code
Display Code
Display Code
Display Code
Display Code
Display Factory
Display Factory
Display Factory
Display Factory
Display Factory
  • If we are not declaring wish() method as Synchronized then both threads will be executed simultaneously and hence we will get irregular output.
  • If we declare wish() method as synchronized then at a time only 1 thread is allow to execute wish() method on the given display object. Hence we will get regular output.

Case Study :

package com.example.thread;/**
* @author code.factory
*
*/
public class SynchronizedTest {
public static void main(String... args) {
Display d1 = new Display();
Display d2 = new Display();
MyThread t1 = new MyThread(d1, "Code");
MyThread t2 = new MyThread(d2, "Factory");
t1.start();
t2.start();
}
}
class Display {
public synchronized void wish(String name) {
for(int i=0; i<5; i++) {
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(name);
}
}
}
class MyThread extends Thread {
Display d;
String name;
public MyThread(Display d, String name) {
this.d = d;
this.name = name;
}
public void run() {
d.wish(name);
}
}

Output :

Code
Factory
Code
Factory
Factory
Code
Code
Factory
Code
Factory
  • Even though wish() method is Synchronized we will get irregular output because threads are operating on different Java objects.
  • Conclusion : If multiple threads are operating on same Java object then Synchronization is required. If multiple threads are operating on mutiple Java objects Synchronization is not required.

--

--