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; } }
Instead of using synchronizedor volatilehere, I personally used AtomicInteger:
synchronized
volatile
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 ...)
get
set
getX
setX
, , . , int, ( , ). , , : thread A , B , .
int
, AtomicInteger. , .
Volatile . . Synchronized Synchronized.
Volatile
Synchronized
:
setX, getXmethod.Do Synchronized, ?
, . , Thread2 getX , Thread1 setX, , , wait() notify().
wait()
notify()
Volatile ?
, , . , Thread2 getX, setX, Thread, Volatile, Thread2 x.
Thread
x