Java: how to use synchronized and unstable

I have two threads. The first thread calls the setX method, the second calls the getX method. Should I install methods synchronously, although I only have one stream of letters? Can I also solve the problem with my second class and mutable variable?

public class Test {
    private int x;  

    public synchronized  void setX(int x) {
        this.x = x;
    }

    public synchronized  int getX() {
        return this.x;
    }
}

public class Test2 {
    private volatile int x; 

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return this.x;
    }
}
+5
source share
3 answers

Instead of using synchronizedor volatilehere, I personally used AtomicInteger:

public class Test {
    private final AtomicInteger x = new AtomicInteger();  

    public void setX(int value) {
        x.set(value);
    }

    public int getX() {
        return x.get();
    }
}

(Please note that I also fixed your get/ set- was previously installed getX, and your setXreceived ...)

+7
source

, , . , int, ( , ). , , : thread A , B , .

, AtomicInteger. , .

+1

Volatile . . Synchronized Synchronized.

:

setX, getXmethod.Do Synchronized, ?

, . , Thread2 getX , Thread1 setX, , , wait() notify().

Volatile ?

, , . , Thread2 getX, setX, Thread, Volatile, Thread2 x.

0

All Articles