When using multiple threads, improper, will result in code execution is very different now imagine if you use the
Look at the following piece of code:
thread class:
class JymThread1 implements Runnable{
private int number;
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+getNumber());
}
public int getNumber(){
return number++ ;
}
}
Test categories:
public class JymIncrementTest {
public static void main(String[] args) {
JymThread1 jymThread = new JymThread1();
for(int i =0;i<10;i++){
new Thread(jymThread).start();
}
}
}
Results: There are two threads to read the same data, the result is obviously problematic
approach:
AtomicInteger using the read variable classes is atomic class
After modifying the code:
class JymThread1 implements Runnable{
private AtomicInteger number = new AtomicInteger(0);
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":"+getNumber());
}
public int getNumber(){
// 先获取,在递增
return number.getAndIncrement();
}
}
Test code the same
results: