Java – race conditions occur even after synchronization

I'm trying to run multiple threads I have obviously obtained the competitive conditions and can solve it as follows:

final Data data = new Data();
for (int i = 0; i < numberOfThreads; i++) {
    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            //using this sync block to stop the race condition 
            synchronized (data){
                final int value = data.getValue();
                data.setValue(value + 1);
            }
        }
    });
    thread.start();
}

But I don't want to synchronize on this block, but I want to process it in the data class So I deleted the above synchronization block and synchronized the get and set methods in the data class, as shown below, but this will still lead to race conditions Why is this problem even if I have synchronized?

public class Data {

    private int value;

    public synchronized int getValue(){
        return this.value;
    }

    public synchronized void setValue(int num){
        this.value = num;
    }
}

Solution

Adding synchronization to individual methods is similar to performing such operations

final Data data = new Data();
for (int i = 0; i < numberOfThreads; i++) {
    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (data){
                final int value = data.getValue();
            }
            synchronized (data){
                data.setValue(value + 1);
            }
        }
    });
    thread.start();
}

The thread can be very obviously stuck between get and set To solve this problem, you need to add a new synchronized method to the data class that completes the value 1 task, or wrap two lines in a synchronized block as in code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>