Sure! Let's walk through an example of a Java synchronization scenario demonstrating both object-level synchronization (i.e. using instance methods with the synchronized keyword) and class-level synchronization (i.e. using static synchronized methods or synchronizing on the class object itself).
🔧 Use Case:
We have a shared resource: a printer. Multiple threads (representing users) are trying to print documents. We will:
Use object-level synchronization to prevent multiple threads using the same printer object from printing simultaneously.
Use class-level synchronization to prevent access to a shared static method, such as a logging function.
✅ Java Code Example
java
// Printer.java
public class Printer {
// Object-level synchronized method
public synchronized void printDocument(String docName, int copies) {
for (int i = 1; i <= copies; i++) {
System.out.println(Thread.currentThread().getName() + " is printing " + docName + " copy " + i);
try {
Thread.sleep(500); // simulate time taken to print
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Class-level synchronized (static) method
public static synchronized void logPrint(String message) {
System.out.println("Logging: " + message + " by " + Thread.currentThread().getName());
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Printer sharedPrinter = new Printer();
// Multiple users (threads) sharing the same printer
UserThread user1 = new UserThread(sharedPrinter, "Doc1");
UserThread user2 = new UserThread(sharedPrinter, "Doc2");
user1.setName("User-1");
user2.setName("User-2");
user1.start();
user2.start();
}
}
🧠 Explanation:
printDocument() is an object-level synchronized method. Only one thread at a time can execute this method for the same Printer object.
logPrint() is a class-level synchronized method (static synchronized). It locks on the Printer.class object, so only one thread across all instances can enter this method at a time.
We simulate printing delay with Thread.sleep(), so you can clearly observe synchronization in action.
🧪 Sample Output:
text
User-1 is printing Doc1 copy 1
User-1 is printing Doc1 copy 2
User-1 is printing Doc1 copy 3
Logging: Printed Doc1 by User-1
User-2 is printing Doc2 copy 1
User-2 is printing Doc2 copy 2
User-2 is printing Doc2 copy 3
Logging: Printed Doc2 by User-2
Output may vary depending on how the threads are scheduled, but the synchronized methods ensure print jobs do not interleave.
Let me know if you want an example using synchronized blocks instead of methods!