Here is a simple example:
private long counter = 0; // note this method is NOT synchronized // this will be called by thread A public void increment() { counter++; } // note this method IS synchronized // this will be called by thread B public synchronized long value() { return counter; }
So, I just want to get a good value for counter, rather than a stuck value in the processor cache, because the variable is unstable. The goal is NOT to make the counter volatile so that it does not affect the stream A performing the increments, but only the stream B, which does not bother me when it reads the variable.
counter
For write only, I plan to read the value counterfrom stream B when stream A is already finished ...
, B , counter. . , , B, counter , , , A, , .
, , counter volatile . .
: A , B , A B, A , , A . , Thread A, .
long , B , .
long
. , n n.
AtomicLong .
AtomicLong
, synchornized , :
synchornized
synchornized(this) { counter++; }
( "-" ):
// Thread A counter++ synchronized (this) { finished = true; } // Thread B synchonized (this) { if (finished) { // you can read counter here } }
, , counter , , , Thread A (, join()):
join()
threadA.join(); // you can read counter here
. , Thread B . increment() - () - .
Thread B
increment()
, , , ., . . , , .
, , , .
, . . , , .
Source: https://habr.com/ru/post/1533863/More articles:Django Debug toolbar appears, but panels return 404 - djangoRoR - select the tag with include_blank disabled - selectHow to make Flowplayer play automatically in Android WebView? - jquerySpeed up copying in java - javaAndroid KitKat (4.4) autoplay video no longer works in webview - androidне удалось установить шпион на HttpSession/Mockito - javaHow to use instance variable in Spock Test section - spockFlask-SQLAlchemy and Flask-Restless don't force grandchildren - pythonFailed to fulfill target org.apache.maven.plugins: maven-compiler-plugin: 2.0: compile - javaJbuilder turn & in \ - jsonAll Articles