Synchronization in Java
In multithreading, synchronization is important to make sure multiple threads safely work on shared
resources. Without synchronization, data can become inconsistent or corrupted if multiple threads
access and modify shared variables at the same time. In Java, it is a mechanism that ensures that
only one thread can access a resource at any given time. This process helps prevent issues such as
data inconsistency and race conditions when multiple threads interact with shared resources.
Example: Below is a Java Program to demonstrate synchronization.
class Counter {
private int c = 0; // Shared variable
// Synchronized method to increment counter
public synchronized void inc() {
c++;
// Synchronized method to get counter value
public synchronized int get() {
return c;
public class Geeks {
public static void main(String[] args) {
Counter cnt = new Counter(); // Shared resource
// Thread 1 to increment counter
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
});
// Thread 2 to increment counter
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
});
// Start both threads
[Link]();
[Link]();
// Wait for threads to finish
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
// Print final counter value
[Link]("Counter: " + [Link]());