Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
576 views

I'm working on a Java multithreading project where multiple threads need to access and modify a shared resource. I've encountered synchronization issues and need guidance on how to ensure thread safety. Here's a simplified version of my code:

[code]

public class SharedResource {
    private int value = 0;

    public int getValue() {
        return value;
    }

    public void increment() {
        value++;
    }
}

public class MyThread extends Thread {
    private SharedResource sharedResource;

    public MyThread(SharedResource sharedResource) {
        this.sharedResource = sharedResource;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            sharedResource.increment();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        SharedResource sharedResource = new SharedResource();
        MyThread thread1 = new MyThread(sharedResource);
        MyThread thread2 = new MyThread(sharedResource);

        thread1.start();
        thread2.start();

        // Wait for both threads to finish
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final value: " + sharedResource.getValue());
    }
}
[/code]

In this code, two threads (thread1 and thread2) are concurrently incrementing a shared value in the SharedResource class. However, I'm experiencing unexpected results due to race conditions.

How can I modify this code to ensure that access to the increment method is synchronized, preventing race conditions and guaranteeing the correct final value of value? Please provide a Java code example with explanations for achieving thread safety in this scenario. Thank you for your assistance!

in Competitive-Programming by Expert (650 points) | 576 views

Please log in or register to answer this question.