0% found this document useful (0 votes)
9 views2 pages

Java Thread Synchronization Explained

The document explains the importance of synchronization in Java for safe multithreading, ensuring that only one thread can access a shared resource at a time to prevent data inconsistency and race conditions. It includes a Java program example demonstrating a synchronized counter class with methods to increment and retrieve the counter value. The program creates two threads that increment the counter concurrently, illustrating the use of synchronization in practice.

Uploaded by

sumanmondal0907
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Java Thread Synchronization Explained

The document explains the importance of synchronization in Java for safe multithreading, ensuring that only one thread can access a shared resource at a time to prevent data inconsistency and race conditions. It includes a Java program example demonstrating a synchronized counter class with methods to increment and retrieve the counter value. The program creates two threads that increment the counter concurrently, illustrating the use of synchronization in practice.

Uploaded by

sumanmondal0907
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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]());

You might also like