Synchronized Method Explanation
Synchronized Method Explanation
Code Breakdown
1. Class TestSynchronization2
This is the main class where the program's execution begins. It demonstrates the creation and
interaction of threads with a shared object.
2. The main Method
Step 1: Create a shared Table object
java
t1.start();
t2.start();
The start() method begins the execution of run() methods in both MyThread1 and
MyThread2.
Synchronization in Action
Both threads (t1 and t2) are operating on the same shared Table object (obj).
The synchronized keyword in the printTable method ensures that only one thread at a time
can execute the method for the shared object.
If t1 is printing the multiplication table of 5, t2 must wait until t1 finishes. Only after t1 is
done, t2 can execute printTable(100).
Expected Output
When the program is executed, the output will be:
5
10
15
20
25
100
200
300
400
500
This output is not interleaved because the printTable method is synchronized, ensuring serialized
access to the method.
5
100
10
200
15
300
20
400
25
500
This happens because both threads are accessing the shared object (obj) simultaneously without
any synchronization mechanism.
Summary
This program demonstrates how multiple threads can safely operate on a shared object by using
synchronization. The synchronized keyword ensures that only one thread can execute the critical
section (printTable method) at a time, thereby maintaining consistent behavior.