1、普通变量线程不安全代码
public class TestAtomicInteger {
public static int count = 0 ;
public static void main ( String [ ] args) throws InterruptedException {
TestCount testCount = new TestCount ( ) ;
Thread threadA = new Thread ( testCount) ;
Thread threadB = new Thread ( testCount) ;
threadA. start ( ) ;
threadB. start ( ) ;
threadA. join ( ) ;
threadB. join ( ) ;
System . out. println ( count) ;
}
public static class TestCount implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 10 ; i++ ) {
try {
Thread . sleep ( 100 ) ;
} catch ( InterruptedException e) { }
count += 1 ;
}
}
}
}
结果不符合预期
2、AtomicInteger 实现代码
public class TestAtomicInteger {
public static AtomicInteger atomicInteger = new AtomicInteger ( 0 ) ;
public static void main ( String [ ] args) throws InterruptedException {
TestCount testCount = new TestCount ( ) ;
Thread threadA = new Thread ( testCount) ;
Thread threadB = new Thread ( testCount) ;
threadA. start ( ) ;
threadB. start ( ) ;
threadA. join ( ) ;
threadB. join ( ) ;
System . out. println ( atomicInteger. get ( ) ) ;
}
public static class TestCount implements Runnable {
@Override
public void run ( ) {
for ( int i = 0 ; i < 10 ; i++ ) {
try {
Thread . sleep ( 100 ) ;
} catch ( InterruptedException e) { }
atomicInteger. getAndAdd ( 1 ) ;
}
}
}
}
结果符合预期