Page 168 - CTS - CSA TP - Volume 2
P. 168
COMPUTER SOFTWARE APPLICATION - CITS
CounterWithSync counter = new CounterWithSync();
IncrementThreadWithSync thread1 = new IncrementThreadWithSync(counter);
IncrementThreadWithSync thread2 = new IncrementThreadWithSync(counter);
thread1.start();
thread2.start();
}
}
Explanation:
1 CounterWithSync Class:
• This class represents a counter with a private count variable.
• The increment() method is synchronized, which means only one thread can execute this method at a time.
• Inside the increment() method, a loop iterates five times, each time incrementing the count by one.
2 IncrementThreadWithSync Class:
• This class extends the Thread class and represents a thread that increments the counter.
• It has a reference to the CounterWithSync object.
3 MultithreadingWithSyncExample Class:
• This class contains the main() method, which serves as the entry point of the program.
• Inside main():
• An instance of CounterWithSync named counter is created.
• Two instances of IncrementThreadWithSync, thread1 and thread2, are created with a reference to the
counter object.
• Both threads are started concurrently using the start() method.
4 Output:
• Since the increment() method is synchronized, only one thread can execute it at a time.
• Thus, the output will show the interleaved execution of the two threads incrementing the counter.
• Each thread displays the count before and after incrementing it, ensuring that the counter is incremented
in a thread-safe manner.
5 Thread Safety:
• Synchronization ensures that only one thread can execute the critical section of code (in this case, the
increment() method) at a time.
• This prevents race conditions and ensures that the shared resource (count variable) is accessed in a
thread-safe manner.
This program demonstrates how to use synchronization in Java to ensure thread safety when multiple threads
access shared resources concurrently. It’s essential for preventing data corruption and maintaining the integrity
of shared data in multithreaded environments.
153
CITS : IT & ITES - Computer Software Application - Exercise 105