Reference: https://fangjian0423.github.io/2016/03/16/java-AtomicInteger-analysis/
Http://www.cnblogs.com/549294286/p/3766717.html
A recent interview encountered a programming problem, requiring two threads to alternately print the number of [0,100], one of which only prints odd numbers, the other only print even, and gives a particularly obvious hint Atomicinteger, when I was thinking that it was a question, but after the recall because handwriting and did not remember all the API, Many places are not perfect, so the interviewer finally let me explain, back again with the IDE to write once more smooth, problem-solving ideas:
- Define THREAD0 output odd, thread1 output even
- THREAD0, if the current value is even, enter the waiting state and wake up Thread1
- Thread1 is executed, if the current value is odd, enter the waiting state and wake up thread0
- Loop executes the previous two steps until the current value reaches 100
ImportJava.util.concurrent.atomic.AtomicInteger;/*** @Description: Test Atomicinteger*/ Public classAtomicintegertest {Private StaticAtomicinteger num =NewAtomicinteger (0); Public Static voidMain (string[] args) {mythead thread0=NewMythead (1); Mythead Thread1=NewMythead (0); Thread0.start (); Thread1.start (); } Public Static classMytheadextendsThread {Private intv; PublicMythead (intv) { This. v =v; } @Override Public voidrun () {synchronized(num) { while(Num.get () < 100) { if(v = = 1) { if(Num.get ()% 2 = = 0) { Try{num.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } Else{System.out.println (Num.incrementandget ()); Num.notifyall (); } } Else if(v = = 0) { if(Num.get ()% 2 = = 1) { Try{num.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } Else{System.out.println (Num.incrementandget ()); Num.notifyall (); } } } } } }}
From the Atomicinteger class source can be seen, it defines a volatile variable value is used to store values, and all operations with the use of unsafe class operations to complete, unsafe class of many operations are CAs, can be understood as self-optimistic lock, There is an ABA problem with optimistic locking, but since Atomicinteger holds an int element, this problem can be ignored, so it can be considered thread-safe. However, for atomicreference, the ABA problem can lead to fatal problems, so there are atomicstampedreference classes to solve this problem.
Java multithreaded series one--atomic class